如何在数组中找到第一个空闲键

时间:2014-02-27 17:39:14

标签: php arrays

我们都知道数组实际上是PHP中的有序树。鉴于此,数组索引(整数键)不需要任何严格的顺序,甚至根本不存在。所以,给出一个像:

这样的数组
array( 1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E', 0 => 'F' )

如何在不重新索引数组的情况下确定第一个空键的最低(非负)整数?在这种情况下,它将是4

7 个答案:

答案 0 :(得分:5)

while循环的简单解决方案:

function firstFreeKey($array)
{
  $i = 0;
  while(isset($array[$i])) $i++;
  return $i;
}

$array = array( 1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E', 0 => 'F' );

echo firstFreeKey($array);

输出:

4

答案 1 :(得分:1)

第一种方法对数组越来越感兴趣。

// STUPID FANCY WAY (playing with arrays)
$array = array( 1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E', 0 => 'F' );
// fetch existing keys
$keys = array_keys($array);
// build a range with all keys (between min and max)
$keys_all = range(min($keys), max($keys));
// difference between all and existing
$keys_diff = array_diff($keys_all, $keys);
// fetch the first in difference (min)
$min_key = reset($keys_diff);
// output it
var_dump($min_key);

第二种方法实际上是可行的,因为它不需要额外的数组在内存中。

// PROPER WAY (not extra array operations)
$array = array( 1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E', 0 => 'F' );
// fetch existing keys
$keys = array_keys($array);
// nullify first
$min_key = null;
// loop all keys and find missing one (skip 1st and last, they totally exist!)
for($key = ($min = min($keys)) + 1, $max = max($keys); $key < $max; ++$key){
    if(!isset($array[$key])){
        $min_key = $key;
        break;
    }
}
// output it
var_dump($min_key);

我会解释评论是否不够。

PS 此方法处理最小键值不是0时的情况。因此,它与范围minmax无关。显然,键需要是整数。

答案 2 :(得分:0)

$a = array( 1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E', 0 => 'F' );
for($i = 0, $l = count($a); $i < $l; $i++) if(!array_key_exists($i, $a)) break;
echo $i; // 4

答案 3 :(得分:0)

$foo = array(1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E', 0 => 'F');
$bar = array(1 => 'A', 4 => 'Z', 2 => 'L', 3 => 'N');

function firstFreeKey($array)
{
    ksort($array);
    for ($i = 0; $i <= count($array); $i++) {
        if (!isset($array[$i])) {
            return $i;
        }
    }
    return count($array) + 1;
}

function firstFreeKeyNotZero($array)
{
    $i = min(array_keys($array));
    while (isset($array[$i])) {
        $i++;
    }
    return $i;
}

echo firstFreeKey($foo); //returns 4
echo firstFreeKey($bar); //returns 0
echo firstFreeKeyNotZero($foo); //returns 4
echo firstFreeKeyNotZero($bar); //returns 5

编辑:根据CodeAngry的要求添加了不从0开始的情况

答案 4 :(得分:0)

可能是最长的答案之一,但解释最多。

$Jumbled_Arr = array(
1 => "test",
3 => "another",
4 => "t",
7 => "kfkfk",
9 => "fk"



);
function GetMissingKey($Array,$Return_Type = false){

    // Get the Maximum Key Value
    $Max_Key = max(array_keys($Array));
        // Treat this as the default array index, as all numerical arrays start at a 0 key set
        $Counter = 0;
        // A Blank array to be maniuplated
    $Generated_Array = array();
        // Generate a full array based on the maximum value and the array index, this will create a keyset from 0 to the highest value 
    while ($Counter < $Max_Key){
            $Generated_Array[] = $Counter;
        $Counter++;
    }   

    // Discover the differences between the correctly formed array and the specified array keys 
    $Missing_Key = array_diff($Generated_Array,array_keys($Array));

            // Work with the second parameter, as the settings. 
        if ($Return_Type === true){
        // If set to true, we are expecting more than 1 free key within the array, so we will return the entire array 
            return $Missing_Key;
        }elseif ($Return_Type === false){
        // If set to false (or blank) we are expecting a single free key to be discovered & we will return it as an imploded array
            return implode($Missing_Key);
        }
}
    print_R(GetMissingKey($Jumbled_Arr,true));

如果将true传递给此函数,则将返回一个缺少键的数组。

如果传递了false,那么将返回一个整数(如果期望返回多个键,则要小心)。

答案 5 :(得分:0)

你有没有试过像

这样的东西
echo min(array_keys($array));

array_keys返回数组的键列表,min确定数组中的最低值。

扩展以下评论:

由于数组是连续的int值,您可以执行以下操作

$keys = array_keys($array);
$arr2 = range(0,max($keys));

// diff gets the missing elements
$missing = array_diff($arr2,$keys);

echo $missing[0];

不确定这种暴力的表现,但可以进行测试。

答案 6 :(得分:0)

获取所有免费密钥:

$aArray = array(1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E');
$iMaxKey = 7; //max key you will need
$aAllKeys = range(0, iMaxKey); //create array(0,1,2,3,4,5,6,7);
$aAllFreeKeys = array_diff_key($aAllKeys, $aArray); //will be: array(0,4,7);

现在如果您需要第一个免费密钥:

$iKey = array_shift($aAllFreeKeys);