PHP compare array

后端 未结 17 1818
萌比男神i
萌比男神i 2020-11-28 12:19

Is there anyway to compare arrays in php using an inbuilt function, short of doing some sort of loop?

$a1 = array(1,2,3);
$a2 = array(1,2,3);

if (array_are_         


        
17条回答
  •  醉话见心
    2020-11-28 13:19

    If you do not care about keys and that just the values then this is the best method to compare values and make sure the duplicates are counted.

    $mag = '{"1":"1","2":"2","3":"3","4":"3"}';
    $mag_evo = '1|2|3';
    
    $test1 = array_values(json_decode($mag, true));
    $test2 = array_values(explode('|', $mag_evo));
    
    if($test1 == $test2) {
        echo 'true';
    }
    

    This will not echo true as $mag has 2 values in the array that equal 3.

    This works best if you only care about the values and keys and you do not care about duplication. $mag = '{"1":"1","2":"2","3":"3","4":"3"}'; $mag_evo = '1|2|3';

    $test1 = json_decode($mag, true);
    $test2 = explode('|', $mag_evo);
    
    // There is no difference in either array.  
    if(!array_diff($test1, $test2) && !array_diff($test2, $test1)) { 
        echo 'true';
    }
    

    This will return true as all values are found in both arrays, but as noted before it does not care about duplication.

提交回复
热议问题