phparrayssorting

How to check if two indexed arrays have same values even if the order is not same?


I want to compare two indexed arrays as such that values will be same for two arrays but order may differ, for example i tried doing this but it simply 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

above example returns match Found and that is because sort() returns 1 if i try sorting indexed array, and both $a and $b contains 1 after sorting resulting in condition being true which is totally wrong, this trick does not seems to work either, i tried with many different sorting function like asort(), arsort() etc, but none seems to work.

what is the workaround for this?

thank you


Solution

  • Instead of comparing the return values of sort, why don't you just compare the arrays after they have been sorted?

    $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 still count as equal. You must also compare the array keys if this is an issue.