I have two arrays, $a and $b here, and need to check if they contain exactly the same elements (independently of the order). I am thinking of using
if (sizeof($a)==sizeof($b) AND array_diff($a,$b)==array())
{
}
But I am new to PHP, so I wonder: Is there a better way?
Since I need to use them as sets, maybe I should not use arrays at all but something else.
The accepted answer fails to account for duplicates. Here is my take
The accepted answer is wrong! It will fail on: https://3v4l.org/U8U5p
$a = ['x' => 1, 'y' => 2]; $b = ['x' => 1, 'y' => 1];
Here is a correct solution:
Plus quite extensive unit tests: https://3v4l.org/m6lHv
@update:
Extensive unit test of @ircmaxell answer: https://3v4l.org/5ivgm
Extensive unit test of @Jon anwser: https://3v4l.org/CrTgQ
If you think of the arrays as sets:
Then your approach is almost correct (you need to drop the equality test for the element count).
If it matters that the arrays contain multiple copies of the same element:
Then your approach is not correct. You need to sort the arrays with
sort
and then compare them with===
. This should be faster, as it can abort the comparison the moment it sees one difference without going over the whole arrays.Update:
Clarified exactly when the OP's approach would be correct or not, also incorporated the suggestion that
sort
would be probably better thanasort
here.Well, we can do something like this:
The reason it works, is that
array_merge
will make a big array that has all the elements of both$a
and$b
(all the elements that are in either$a
,$b
, or both).array_intersect
will create an array that has all the elements that are in both$a
and$b
only. So if they are different,, there must be at least one element that does not appear in both arrays...Also note that
sizeof
is not an actual function/construct, it's an alias. I'd suggest usingcount()
for clarity...Just for your amusement I'll add an example that demonstrates that your conditions is not correct:
Test it.
I would suggest using a different model. Maybe adding the elements as keys of the array, but this is possible only if they are integers or strings.
This will enforce uniqueness. With this model you can use your condition on
array_keys($arr)
.