Say i have the following array: 1,2,3,6,8
I need to find that the next missing number is 4
What is the easiest and quickest way to perform this ?
Iterating the array and checking in_array()
should do it.
$missing = null;
for ($i = 1; $i <= 10; $i++) {
if (!in_array($i, $myArray)) {
$missing = $i;
break;
}
}
if (!is_null($missing)) {
// hit
}
$missing = array_diff(range(min($myArray), max($myArray)), $myArray);
$nextMissing = (!empty($missing)) ? array_shift($missing) : max($myArray) + 1;
The Question is worded poorly but from my understanding you have 1,2,3
and then you need to check that next value should be 4
$prev = array[0];
for($i = 1; $i < count(array); $i++){
if(array[$i] != prev+1) return (prev+1)
}
I would do it like this (if the array is sorted):
$array = array(1, 2, 3, 6, 8);
$size = count($array);
$missing = 0;
$firstval = $array[0];
for ($i = 0; $i < $size; ++$i) {
if ($firstval++ != $array[$i]) {
$missing = $firstval - 1;
break;
}
}
if ($missing != 0) echo $missing.' is missing'.PHP_EOL;
Which gives:
4 is missing