How can I check if two indexed arrays have the same values ββeven if the order is not the same as in PHP?
I want to compare two indexed arrays in such a way that the values ββare the same for the two arrays, but the order may be different, for example I tried to do this but it just doesn't work.
Example 1:
$a = array(1,2,3,4,5);
$b = array(1,2,3,5,4);
echo ($a == $b) ? 'Match Found' : 'No Match Found';
//Returns No Match Found
Example 2: (tried sorting the array, but it doesn't sort)
$a = array(1,2,3,4,5);
$a = sort($a);
$b = array(1,2,3,5,4);
$b = sort($b);
echo ($a === $b) ? 'Match Found' : 'No Match Found';
//Returns Match Found
the above example returns the match Found, and this is because it sort()
returns 1, if I try to sort an indexed array, and both $a
and $b
contain 1
after sorting, resulting in the condition being true, which is completely wrong, this trick doesn't seem to work either, I tried many sorting functions like asort()
, arsort()
etc, but none works.
What's the workaround for this?
Thank you
source to share
Instead of comparing the return values sort
, why don't you just compare the arrays after you sort them?
$a = array(1,2,3,4,5);
sort($a);
$b = array(1,2,3,5,4);
sort($b);
echo ($a == $b) ? 'Match Found' : 'No Match Found';
If the arrays have different keys but the same values, they will be considered equal. You should also compare the keys of the array if this is a problem.
source to share