Check if two arrays have the same values

If you don't want to sort arrays but just want to check equality regardless of value order use http://php.net/manual/en/function.array-intersect.php like so:

$array1 = array(2,5,3);
$array2 = array(5,2,3);
if($array1 === array_intersect($array1, $array2) && $array2 === array_intersect($array2, $array1)) {
    echo 'Equal';
} else {
    echo 'Not equal';
}

sort($a);
sort($b);
if ($a===$b) {//equal}

This is a bit late to the party but in hopes that it will be useful:

If you are sure the arrays both only contain strings or both only contain integers, then array_count_values($a) == array_count_values($b) has better time complexity. However, user1844933's answer is more general.


Coming to this party late. I had the same question but didn't want to sort, which was the immediate answer I knew would work. I came up with this simple one-liner which only works for arrays of unique values:

$same = ( count( $a ) == count( $b ) && !array_diff( $a, $b ) )

It's also about a factor of 5 faster than the sort option. Not that either is especially slow, so I would say it is more about your personal preferences and which one you think is more clear. Personally I would rather not sort.

Edit: Thanks Ray for pointing out the fact that this only works with arrays with unique values.

Tags:

Php

Arrays