To compare two arrays while considering duplicate value

后端 未结 4 863
心在旅途
心在旅途 2020-12-20 23:17

i have two arrays

$array1 = array(1, 2,  2, 3);
$array2 = array( 1, 2,  3,4);

and when did :

var_dump(array_diff($array1,         


        
4条回答
  •  太阳男子
    2020-12-21 00:06

    This will get you the desired result:

    $array1 = array(1, 2,  2, 3);
    $array2 = array( 1, 2,  3,4);
    
    $countArray1 = array_count_values($array1);
    $countArray2 = array_count_values($array2);
    
    foreach($countArray1 as $value=>$count) {
        if($count > 1) $dupArray[] = $value;
    }
    
    foreach($countArray2 as $value=>$count) {
        if($count > 1) $dupArray[] = $value;
    }
    
    print_r($dupArray);
    

    Result

    Array
    (
        [0] => 2
    )

    Explanation

    Using array_count_values will count all the values of an array, which would look like:

    Array
    (
        [1] => 1
        [2] => 2
        [3] => 1
    )
    
    Array
    (
        [1] => 1
        [2] => 1
        [3] => 1
        [4] => 1
    )

    We then iterate through each array_count_values to locate values that occur more than once. This will work when you have more than one set of duplicate values:

    $array1 = array(1, 2,  2, 3);
    $array2 = array( 1, 2,  3, 4, 3);
    

    Result

    Array
    (
        [0] => 2
        [1] => 3
    )

提交回复
热议问题