2

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

1

3 Answers 3

4
$a = array(1,2,3,4,5);
$b = array(1,3,2,5,3,4);


if(count($a) == count($b) && count(array_diff($a, $b)) == 0){
    echo "A";
}

Need to do a length check or the two arrays above would come out the same.

edit: better solution.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

This answer would unexpectedly display "Match Found", in this use case:

$a = array(5,1,2,"3",4);
sort($a);
$b = array(1,3,5,"4","2");
sort($b);
echo ($a == $b) ? 'Match Found' : 'No Match Found'; // displays "Match Found"

And this wouldn't (just added the "aa" element to the two arrays):

$a = array(5,1,2,"3",4,"aa");
sort($a);
var_dump($a);
$b = array(1,3,5,"4","2","aa");
sort($b);
var_dump($b); // not same ordering
echo ($a == $b) ? 'Match Found' : 'No Match Found'; // displays "No Match Found"

Better compare apples to apples; convert the two arrays to arrays of strings:

$a = array(5,1,2,"3",4,"aa");
$a = array_map("strval", $a); // conversion to an array of strings
sort($a);
$b = array(1,3,5,"4","2","aa");
$b = array_map("strval", $b); // conversion to an array of strings
sort($b);

echo ($a == $b) ? 'Match Found' : 'No Match Found'; // displays "Match Found"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.