- Related Questions & Answers
- PHP program to find the sum of first n natural numbers that are divisible by a number ‘x’ or a number ‘y’
- PHP program to find the numbers within a given array that are missing
- PHP program to find the average of the first n natural numbers that are even
- PHP program to find the sum of the first n natural numbers who are not powers of a specific number ‘k’
- PHP program to find missing elements from an array
- PHP program to find the sum of cubes of the first n natural numbers
- Find four missing numbers in an array containing elements from 1 to N in C++
- Find four missing numbers in an array containing elements from 1 to N in Python
- PHP program to find the sum of the 5th powers of first n natural numbers
- Program to find first N Iccanobif Numbers in C++
- Program to find all missing numbers from 1 to N in Python
- 8085 program to find the sum of first n natural numbers
- Program to find the sum of first n odd numbers in Python
- PHP program to find the first natural number whose factorial can be divided by a number ‘x’
- PHP program to find the sum of cubes of natural numbers that are odd

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

<?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); ?>

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.

Advertisements