PHP Challenges: Find a missing number(s) from an array
Write a PHP program to find a missing number(s) from an array.
Input : 1,2,3,6,7,8
Explanation :
Sample Solution :
PHP Code :
<?php
// Define a function named missing_number which takes an array $num_list as input
function missing_number($num_list)
{
// Construct a new array containing the range from the first element to the maximum element in $num_list
$new_arr = range($num_list[0], max($num_list));
// Use array_diff to find the missing elements by comparing $new_arr with $num_list
return array_diff($new_arr, $num_list);
}
// Test the missing_number function with different input arrays and print the result
print_r(missing_number(array(1,2,3,6,7,8)));
print_r(missing_number(array(10,11,12,14,15,16,17)));
?>
Explanation:
Here is a brief explanation of the above PHP code:
- The code defines a function named 'missing_number' which takes an array '$num_list' as input.
- Inside the function:
- It constructs a new array '$new_arr' using the 'range()' function, which generates an array containing a range of numbers from the first element of '$num_list' to the maximum element in '$num_list'.
- It then uses the 'array_diff()' function to find the elements that are present in `$new_arr` but missing in '$num_list', effectively finding the missing numbers.
- Finally, it returns the array of missing numbers.
- The function is called twice with different input arrays '(1,2,3,6,7,8)' and '(10,11,12,14,15,16,17)'.
Sample Output:
Array ( [3] => 4 [4] => 5 ) Array ( [3] => 13 )
Flowchart:

Go to:
PREV : Write a PHP program to check if an integer is the power of another integer.
NEXT : Write a PHP program to find three numbers from an array such that the sum of three consecutive numbers equal to zero.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.