Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding first available ID from an array

Tags:

arrays

php

Given an array like this:

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

What is the easiest way to find the first 'available' ID in that array – that is, the first value in the 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 while loops or sorts with temp variables but that's a bit messy, so I'm interested to see if anyone can come up with a 'clever' solution.

like image 598
Tatu Ulmanen Avatar asked Jun 25 '26 21:06

Tatu Ulmanen


1 Answers

My PHP skills are a bit rusty, but couldn't you use range and array_diff:

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

Updated with Tatu Ulmanen's corrections (i told ya my PHP was rusty ;-))

like image 182
Andy E Avatar answered Jun 27 '26 11:06

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!