Is there a built-in function for PHP for me to check whether two arrays contain the same values ( order not important?).
For example, I want a function that returns
You can use array_intersect()
instead of array_diff()
:
$a = array('4','5','2');
$b = array('2','4','5');
$ca = count($a);
$cb = count($b);
$array_equal = ( $ca == $cb && $ca == count(array_intersect($a, $b)) );
Performance wise. solution, where two factors are important:
array_intersect()
is fast.array_intersect()
is fast.Depending on these factors, one method can be two or three time faster than the other. For big arrays with few (or no) matching combinations, or for little arrays with lots of matching, both methods are equivalent.
However, the sort method is always faster, except in the case with little arrays with few or no matching combinations. In this case the array_diff()
method is 30% faster.
The array_diff()
method above won't work.
php.net's manual says that array_diff()
does this:
"Returns an array containing all the entries from array1 that are not present in any of the other arrays."
So the actual array_diff()
method would be:
function array_equal($array1, $array2)
{
$diff1 = array_diff($array1, $array2);
$diff2 = array_diff($array2, $array1);
return
(
(count($diff1) === 0) &&
(count($diff2) === 0)
);
}
However I go with the sort method :D
array_diff looks like an option:
function array_equal($a1, $a2) {
return !array_diff($a1, $a2) && !array_diff($a2, $a1);
}
or as an oneliner in your code:
if(!array_diff($a1, $a2) && !array_diff($a2, $a1)) doSomething();
If the arrays being compared consist of only strings and/or integers, array_count_values allows you to compare the arrays quickly (in O(n)
time vs O(n log n)
for sorting) by verifying that both arrays contain the same values and that each value occurs the same # of times in both arrays.
if(array_count_values($a1) == array_count_values($a2)) {
//arrays are equal
}
You can use array_diff.
$a = array('4','5','2');
$b = array('2','4','5');
if(count(array_diff($a, $b)) == 0) {
// arrays contain the same elements
} else {
// arrays contain different elements
}
However, a problem with this approach is that arrays can contain duplicate elements, and still match.
You only need to compare one-way using array_diff() and use count()
for the inverted relationship.
if (count($a1) == count($a2) && !array_diff($a1, $a2)) {
// equal arrays
}