w3resource logo
php Programming Exercies

PHP Challenges: Find a missing number(s) from an array

PHP Challenges - 1: Exercise-5 with Solution

Write a PHP program to find a missing number(s) from an array.

Input : 1,2,3,6,7,8

Explanation :

PHP: Find a missing number(s) from an array

Sample Solution :

PHP Code :

function missing_number($num_list)
{
 // construct a new array
$new_arr = range($num_list[0],max($num_list));                                                    
// use array_diff to find the missing elements 
return array_diff($new_arr, $num_list);

}
print_r(missing_number(array(1,2,3,6,7,8)));
print_r(missing_number(array(10,11,12,14,15,16,17)));
?>

Sample Output:

Array                                                                                
(                                                                                    
    [3] => 4                                                                         
    [4] => 5                                                                         
)                                                                                    
Array                                                                                
(                                                                                    
    [3] => 13                                                                        
)             

Flowchart:

PHP Flowchart: Find a missing number(s) from an array

PHP Code Editor:

Improve this sample solution and post your code through Disqus