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.
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 ;-))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With