Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

I got a an array like this $ids = array(3,7,6,5,1,8,11) . How do we know the 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

like image 324
angry kiwi Avatar asked Nov 27 '22 07:11

angry kiwi


2 Answers

Here's nice one-liner:

$ids = array(3,5,6,7,8,11);
$missing = array_diff(range(1, max($ids)), $ids);
like image 155
Mark Eirich Avatar answered Dec 05 '22 23:12

Mark Eirich


$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
like image 44
Dan Grossman Avatar answered Dec 05 '22 22:12

Dan Grossman