PHP compare array

后端 未结 17 1824
萌比男神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:15

    @Cleanshooter i'm sorry but this does not do, what it is expected todo: (so does array_diff mentioned in this context)

    $a1 = array('one','two');
    $a2 = array('one','two','three');
    
    var_dump(count(array_diff($a1, $a2)) === 0); // returns TRUE
    

    (annotation: you cannot use empty on functions before PHP 5.5) in this case the result is true allthough the arrays are different.

    array_diff [...] Returns an array containing all the entries from array1 that are not present in any of the other arrays.

    which does not mean that array_diff is something like: array_get_all_differences. Explained in mathematical sets it computes:

    {'one','two'} \ {'one','two','three'} = {}
    

    which means something like all elements from first set without all the elements from second set, which are in the first set. So that

    var_dump(array_diff($a2, $a1));
    

    computes to

    array(1) { [2]=> string(5) "three" } 
    

    The conclusion is, that you have to do an array_diff in "both ways" to get all "differences" from the two arrays.

    hope this helps :)

提交回复
热议问题