如何在不使用PHP函数的情况下从数组中查找缺失的数字?

时间:2019-07-06 05:36:21

标签: php

我有两个数组,即$arr1 and $arr2,在这里我想找到$arr1中不存在的$arr2缺失值,而不使用array_diff(), count(), explode(), implode()等函数。我可以这样做吗?请帮助我。

代码:

<?php
    $arr1 = array('2','3','4','5');
    $arr2 = array('1','6','7','8');

    $array = array_diff($arr1,$arr2);
    print_r($arr2);
?>

2 个答案:

答案 0 :(得分:1)

可以通过以下方式实现要求:

$arr1 = array('2','3','4','5');
$arr2 = array('1','6','7','8');

$diff = array();
$diff = $arr1;
$arrayDiff = array();

foreach($arr1 AS $value) {
    foreach($arr2 AS $val) {
        if ($value == $val) {
           $arrayDiff[] = $value;
           continue;
        }
    } 
}
foreach ($arrayDiff AS  $k=>$v) {
    if (($key = array_search($v, $diff)) !== false) {
        unset($diff[$key]);
    }
}
print_r($diff);

答案 1 :(得分:0)

第一种方法:-

$missingValuesArray = array();
    foreach($arr1 as $arr){
       if(!in_array($arr,$arr2)){
           $missingValuesArray[] = $arr;
       }
    }

    print_r($missingValuesArray);

输出:-https://3v4l.org/UBS9G

第二种方法:-

 $missingValuesArray = array();
    foreach($arr1 as $arr){
        $counter = 0;
        foreach($arr2 as $ar){
           if($arr != $ar){
               $counter++;
           }
        }
        if($counter == sizeof($arr2)){
            $missingValuesArray[] = $arr;
        }
    }

    print_r($missingValuesArray);

输出:-https://3v4l.org/Uu6Ob