PHP 程序来查找数组中的缺失元素
“array_diff”函数可用于查找数组中缺失的元素。
示例
<?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))); ?>
输出
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 )
定义了一个名为“absent”的函数,用于检查最小数字和最大数字,并在此范围内生成一个数组。然后,该函数使用“array_diff”函数返回此数组与原始数组之间的差,从而得到数组中缺失的元素。
广告