I need to find the chronological next number. For example , I have an array :
$numbers = array(1,2,4);
I want function give me the missing chronological number : 3
more example :
$numbers = array(6,7,8,11);
need to give me : 9
Thanks
I need to find the chronological next number. For example , I have an array :
$numbers = array(1,2,4);
I want function give me the missing chronological number : 3
more example :
$numbers = array(6,7,8,11);
need to give me : 9
Thanks
The only way I see doing this is to use sort
on your array, then looping through the entire array.
To insert the number at the specified position in the array, look at this.
Use nickb's answer though - much better!
The solution is simple once you make the assumption that the array is sorted with:
sort( $numbers);
Then, you can get the complete range of numbers, do a difference on the complete set and the input array, and take the first element (which will be the first element that differs):
Since the array is sorted, we can grab the min and max elements like this (we could also call min()
and max()
):
$min = current( $numbers);
$max = end( $numbers);
Now, we use range()
to get the complete set of numbers, then call array_diff()
to find the difference:
$complete = range( $min, $max);
$diff = array_diff( $complete, $numbers);
The first consecutive missing number is in the first element in the difference:
$first_missing = array_shift( $diff);
The benefit here is that $diff
will contain all of the missing numbers between the range of $min
and $max
.
This should do the trick:
<?php
function chrono_trigger($array) {
sort($array, SORT_NUMERIC);
$prev = False;
foreach($array as $num) {
if($prev === False) {
$prev = $num;
continue;
}
if($prev != ($num-1)) {
return $prev+1;
}
$prev = $num;
}
return False;
}
$numbers1 = array(1,2,4); // Should return 3
$numbers2 = array(6,7,8,11); // Should return 9
$numbers3 = array(1,2,3,4); // Shouldn't return anything
// Returns 3
$missing1 = chrono_trigger($numbers1);
var_export($missing1);
// Returns 9
$missing2 = chrono_trigger($numbers2);
var_export($missing2);
// Returns False
$missing3 = chrono_trigger($numbers3);
var_export($missing3);