Skip to content
Advertisement

comparing arrays in php, without caring for the order

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

JavaScript

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.

Advertisement

Answer

The accepted answer is was wrong. It will would fail on: https://3v4l.org/U8U5p

$a = ['x' => 1, 'y' => 2]; $b = ['x' => 1, 'y' => 1];

Here is a correct solution:

JavaScript

Plus quite extensive unit tests: https://3v4l.org/m6lHv

JavaScript

@update:

Extensive unit test of @ircmaxell answer: https://3v4l.org/5ivgm

Extensive unit test of @Jon anwser: https://3v4l.org/CrTgQ

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement