Skip to content

PHPUnit: assert two arrays are equal, but order of elements not important

You can use the assertEqualsCanonicalizing method to compare two arrays and ignore the order of the elements.

Example of using the assertEqualsCanonicalizing method to compare two arrays and ignore the order of the elements in PHPUnit

php
$expected = [3, 2, 1];
$actual = [1, 2, 3];
$this->assertEqualsCanonicalizing($expected, $actual);

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

Alternatively, you can sort both arrays before comparing them using the assertEquals method.

Example of sorting arrays before comparing them with assertEquals in PHPUnit

php
$expected = [3, 2, 1];
sort($expected);
$actual = [1, 2, 3];
sort($actual);
$this->assertEquals($expected, $actual);

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.