PHP program to find the first ‘n’ numbers that are missing in an array


To find the first ‘n’ numbers that are missing in an array, the PHP code is as follows −

Example

 Live Demo

<?php
   function missing_values($my_arr, $len, $n){
      sort($my_arr); sort($my_arr , $len);
      $i = 0;
      while ($i < $n && $my_arr[$i] <= 0)
      $i++;
      $count = 0; $curr = 1;
      while ($count < $n && $i < $len){
         if ($my_arr[$i] != $curr){
            echo $curr , " ";
            $count++;
         }
         else
            $i++;
            $curr++;
      }
      while ($count < $n){
         echo $curr , " ";
         $curr++;
         $count++;
      }
   }
   $my_arr = array(6, 8, 0);
   $len = sizeof($my_arr);
   $n = 5;
   print_r("The missing values of the array are ");
   missing_values($my_arr, $len, $n);
?>

Output

The missing values of the array are 1 2 3 4 5

In the above code, a function named ‘missing_values´ is defined, that takes the array, length, and the first few numbers that are missing from the array.

A variable is assigned to 0 and checked if the first few numbers that need to be found is 0 or more. If it is 0, it is incremented.

A count is assigned to 0, and curr value is assigned to 1. Next, the count value and first ‘n’ elements of array is compared, and the ‘i’th value is compared with the length. If curr is same as one of the elements of the array, the count value is incremented. Otherwise, ‘i’ value is incremented. Outside this function, the array is defined, and ‘len’ variable is assigned to the length of the array.

The first ‘n’ elements is assigned as 5. The function is called by passing these values as parameters, and the output is printed on the console.

Updated on: 17-Aug-2020

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements