PHP program to find the numbers within a given array that are missing

PHPServer Side ProgrammingProgramming

Kickstart HTML, CSS and PHP: Build a Responsive Website

Featured

59 Lectures 8.5 hours

To find the numbers within a given array that are missing, the code is as follows −

Example

Live Demo

<?php
function missing_nums($my_arr,$arr_len, $val) { sort($my_arr); sort($my_arr ,$arr_len);
$i = 0; while ($i < $n &&$my_arr[$i] <= 0)$i++;
$count = 0;$current_num = 1;
while ($count <$k && $i <$arr_len)
{
if ($arr[$i] != $current_num) { echo$current_num , " ";
$count++; } else$i++;
$current_num++; } while ($count < $val) { echo$current_num , " ";
$current_num++;$count++;
}
}
$my_arr =array ( 6, 7, 9 );$arr_len = sizeof($my_arr);$val = 5;
print_r("The missing numbers in the array is ");
missing_nums($my_arr,$arr_len, \$val);
?>

Output

The missing numbers in the array is 1 2 3 4 5

A function named ‘missing_nums’ is defined that checks to see if a number is missing from an array of continuous numbers. It iterates through the array and checks to see the count and the current_num that is being iterated over. If two values can’t be found when 1 is added to the previous number, it is considered to be missing.

Outside the function, the array is defined, its length is assigned to a variable and the number of missing numbers that need to be found is also defined. The function is called by passing these values as parameters and computed output is displayed on the console.

Updated on 02-Jul-2020 07:10:31