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: 2020-08-17T12:15:07+05:30

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements