Home > Article > Daily Programming > PHP check missing numbers in array
PHP checks for possible missing numbers in the array, which can also be understood as calculating the difference between the elements in the two arrays. So here we can achieve it through the two functions range and array_diff in PHP.
Recommended reference study: "PHP Tutorial"
Below we will introduce PHP check arrays with specific code examples. Methods for numbers that may be missing.
The code example is as follows:
<?php //PHP检查数组中可能缺少的数字 function aaa($num_list){ //创建一个数组 $new_arr = range($num_list[0],max($num_list)); //使用array_diff查找缺少的元素 return array_diff($new_arr,$num_list); } echo "<pre class="brush:php;toolbar:false">"; print_r(aaa(array(1,2,3,6,7,8))); print_r(aaa(array(10,11,12,14,15,16,17)));
Here we create an aaa method to calculate the missing numbers in the two arrays in the above code.
The missing elements in the output are as follows:
As shown in the figure, the first array is missing the numbers 4 and 5; the second array is missing Number 13.
Introduction to important functions:
range function means creating an array based on the range, containing the specified elements
Syntax:
range ( mixed $start , mixed $end [, number $step = 1 ] ) : array
Create an array containing cells in the specified range.
Parameter: start represents the first value of the sequence. end represents the value at which the sequence ends. step means that if the step size step is set, it will be used as the step value between units. step should be positive. If step is not set, it defaults to 1.
The return value is the cells from start to end (including start and end) in the returned array.
array_diff functionRepresents the calculation of the difference set of arrays
Syntax:
array_diff ( array $array1 , array $array2 [, array $... ] ) : array
Compares array1 with one or more other arrays, and returns the value in array1 but Values not in other arrays.
Parameters: array1 represents the array to be compared; array2 represents comparison with this array; ... represents more compared arrays.
The return value means returning an array that includes all values in array1 but not in any other parameter array. Note that the key names remain unchanged.
This article is an introduction to the method of checking possible missing numbers in an array in PHP. It is also one of the common PHP interview questions. It is very simple. I hope it will be helpful to friends in need!
The above is the detailed content of PHP check missing numbers in array. For more information, please follow other related articles on the PHP Chinese website!