PHPUnit: Compare two arrays but ignore order of values
27 March 2026 (Updated 27 March 2026)
You want to use the assertEqualsCanonicalizing(array $a, array $b) method.
For example, this test will pass because although the order of the values in $array1 and $array2 are different, they contain the same values:
<?php
declare(strict_types=1);
namespace App\Tests\Unit;
use PHPUnit\Framework\TestCase;
class ArrayComparisonTest extends TestCase
{
public function testArraysAreEqualIgnoringOrder(): void
{
$array1 = [1, 2, 3];
$array2 = [3, 1, 2];
$this->assertEqualsCanonicalizing($array1, $array2);
}
}
Tagged:
PHP tooling