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 me true for the following two inputs:
array('4','5','2')
array('2','4','5')
Edit: I could have sorted the two arrays and compare them, but as I am such a lazy guy, I would still prefer a one-liner that I can pull out and use.
Use the sort() function to sort an array element and then use the equality operator. Use array operator ( == ) in case of Associative array.
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
Check if two arrays are equal or not using Sorting Follow the steps below to solve the problem using this approach: Sort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.
The array_flip() function is used to exchange the keys with their associated values in an array. The function returns an array in flip order, i.e. keys from array become values and values from array become keys. Note: The values of the array need to be valid keys, i.e. they need to be either integer or string.
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();
The best solution is to sort both array and then compare them:
$a = array('4','5','2');
$b = array('2','4','5');
sort($a);
sort($b);
var_dump($a === $b);
As a function:
function array_equal($a, $b, $strict=false) {
if (count($a) !== count($b)) {
return false;
}
sort($a);
sort($b);
return ($strict && $a === $b) || $a == $b;
}
Here’s another algorithm looking for each element of A if it’s in B:
function array_equal($a, $b, $strict=false) {
if (count($a) !== count($b)) {
return false;
}
foreach ($a as $val) {
$key = array_search($val, $b, $strict);
if ($key === false) {
return false;
}
unset($b[$key]);
}
return true;
}
But that has a complexity of O(n^2). So you better use the sorting method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With