PHP array(3,5,6,7,8,11) how do we know the missing values are 1,2,4,9,10
I got a an array like this $ids = array(3,7,6,5,1,8,11) . How do we know th开发者_如何学JAVAe missing values are 2,4,9,10 ?
My expecting $ids values 1,2,3,4,5,6,7,8,9,10,11 and order doesn't matter, it could be 3,5,6,1,2,4,8,9,10,11.
I don't need to fill my array with the missing values I just want to know who's missing
Here's nice one-liner:
$ids = array(3,5,6,7,8,11);
$missing = array_diff(range(1, max($ids)), $ids);
$numbers = array(3,5,6,7,8,11);
$missing = array();
for ($i = 1; $i < max($numbers); $i++) {
if (!in_array($i, $numbers)) $missing[] = $i;
}
print_r($missing); //1,4,9,10
Sort of a poorly defined question, but I'll bite.
Why not grab the lowest (min()
) and highest (max()
) values in the array, then walk through the array in a for loop, adding missing values to a second array as they're found?
On second thought, there's an even better way: you could preload the second array using range()
, passing in the low/high values from the first and last indexes, then use array_diff_key()
to find the missing values.
This is all assuming I've understood your question correctly, and you just want to fill in missing values using the already defined array to define the boundaries.
$ids = array(3,7,6,5,1,8,11);
//var_dump(max($array));
$arr = range(1,max($ids));
$missing = array_diff($arr,$ids);
var_dump($missing);
精彩评论