0

I am trying to find missing in array.

with this code

<?php                       
     $no = array(1,2,3,5,6,7);
     $max=max($no);
     for($x=0; $x<=$max; $x++){
       if(!in_array($x,$no)){ 
       $id = $x;
       }else{
       $id = $x+1;
       }                        
     }
     echo '<pre>'; print_r($id);
?>

but the result is

8

someone can help me?

2
  • your trying to store the missing number to another variable right? Commented Jan 18, 2020 at 1:52
  • Do you want to find the first missing value or all the missing values? Do the missing values start at 0 or the minimum value in the array? Commented Jan 18, 2020 at 2:07

1 Answer 1

1

You are executing your loop to the end, regardless of whether you find a missing value or not. Thus $id will always be $max+1. You need to break out of the loop when you find a missing value (or if you want all missing values, push the missing value to an array). However, the code can be more simply implemented using array_diff on a range from 0 to the maximum value in $no:

$no = array(1,2,3,5,6,7);
$max = max($no);
// you may want to use min($no) here
$min = 0;
$missing = array_diff(range($min, $max), $no);
// print all missing values in the range
print_r($missing);
// if you only want the first missing value
echo min($missing);

Output:

Array
(
    [0] => 0
    [4] => 4
)
0

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.