Search for the first available identifier from an array

For such an array:

Array => (
  [0] => 1,
  [1] => 2,
  [2] => 3,
  [3] => 5,
  [4] => 6
)

What is the easiest way to find the first “available” identifier in this array — that is, the first value in a sequence [1,2,3...n]that does not exist in the array? In this case, the correct answer would be 4.

I can do this using some loops or sorts with temporary variables, but this is a bit dirty, so I am interested to know if anyone can come up with a “smart” solution.

+3
source share
5 answers

My PHP skills are a bit rusty, but could you use rangeand array_diff:

$missing = array_diff(range(1, end($myArray)+ 1), $myArray);
echo $missing[0];

( , PHP ; -))

+6

, , .

- :

sort($array);
$next_available = array_shift($array);
foreach($array as $_k) {
    ++$next_available;
    if($_k > $next_available) {
        break;
    }
}
echo "Next available index: {$next_available}";
+1

, , - , :

sort( $array );
$range = range( reset( $array ), end( $array ) );
$diff = array_diff( $range, $array );
$result = null != ( $result = array_shift( $diff ) ) ? $result : end( $array ) + 1;
+1

, :

$values = array_values($id_array);
$values[] = max($values) + 1;
$combined = array_values(array_flip($values) + array_keys($values));
$missing = isset($combined[count($values) + 1])
    ? $combined[count($values) + 1]
    : end($values);

, . range() , array_diff() . , , ( end($values) false, , ).

, , . array_diff() ( range()) , .

+1

if your array uses only a numeric key and without a hole, you can do $next_id = count($your_array)

If there are holes, you can try

$keys = array_keys($your_array);
rsort($keys);
$next_id = empty($keys)?0:($keys[0]+1);
0
source

Source: https://habr.com/ru/post/1736463/


All Articles