PHP array (3,5,6,7,8,8,11), as we know, the missing values ​​are 1,2,4,9,10

I got an array like this $ ids = array (3,7,6,5,1,8,11). How do we know that the missing values ​​are 2,4,9,10?

My expected values ​​are $ lids 1,2,3,4,5,6,7,8,9,10,11 and the order doesn't matter, it could be 3,5,6,1,2,4, 8,9 10.11.

I do not need to populate my array with missing values. I just want to know who is missing

+3
source share
4 answers
$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
+3
source

Here's a nice one-liner:

$ids = array(3,5,6,7,8,11);
$missing = array_diff(range(1, max($ids)), $ids);
+22
source

, .

(min()) (max()) , for, ?

, : using range(), / , array_diff_key(), .

All of this assumes that I understood your question correctly, and you just want to fill in the missing values ​​using an already defined array to determine the boundaries.

+2
source
$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);
-1
source

Source: https://habr.com/ru/post/1790147/


All Articles