To find a missing number in an array using PHP, you can use a loop to iterate through the array and check for the missing number. Here’s a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php function findMissingNumber($arr) { $n = count($arr) + 1; // Since one number is missing, the array size is n+1 $totalSum = ($n * ($n + 1)) / 2; // Sum of first n natural numbers $arrSum = array_sum($arr); // Sum of the elements in the array $missingNumber = $totalSum - $arrSum; return $missingNumber; } // Example usage $array = [1, 2, 4, 6, 3, 7, 8]; $missingNumber = findMissingNumber($array); echo "The missing number is: " . $missingNumber; ?> |
In this PHP script, the findMissingNumber() function takes an array as input and calculates the missing number by finding the difference between the expected sum of numbers (using the formula for the sum of the first n natural numbers) and the sum of the elements in the array.
Note: This program assumes that there is exactly one missing number in the array, and the array contains distinct positive integers starting from 1.