PHP program to find missing elements from an array

PHPServer Side ProgrammingProgramming

The ‘array_diff’ function can be used to find the elements that are missing from the array.

Example

 Live Demo

<?php
   function absent($my_list)
   {
      $my_array = range(min($my_list), max($my_list));
      return array_diff($my_array, $my_list);
   }
   echo "Elements missing from first array are ";
   print_r(absent(array(45, 48, 51, 52, 53, 56)));
   echo "Elements missing from second array are ";
   print_r(absent(array(99, 101, 104, 105)));
?>

Output

Elements missing from first array are Array
(
   [1] => 46
   [2] => 47
   [4] => 49
   [5] => 50
   [9] => 54
   [10] => 55
)
Elements missing from second array are Array
(
   [1] => 100
   [3] => 102
   [4] => 103
)

A function named ‘absent’ is defined that checks to see the minimum number and the maximum number and generates an array within that range. The function then returns the difference between this array and the original array, using the ‘array_diff’ function, that gives the missing elements from the array.

raja
Published on 01-Jul-2020 10:52:06
Advertisements