Last active
August 9, 2022 15:08
-
-
Save pokap/ac5fce3570c9bec3a87a8908bcbd0bbc to your computer and use it in GitHub Desktop.
[PHPunit] assert two arrays are equal, but ignore orders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait ArrayTestCaseTrait | |
{ | |
/** | |
* Asserts that two associative arrays are similar. | |
* | |
* Both arrays must have the same indexes with identical values | |
* without respect to key ordering | |
* | |
* @param array $expected | |
* @param array $array | |
*/ | |
protected function assertArraySimilar(array $expected, array $array) | |
{ | |
$this->assertTrue(count(array_diff_key($array, $expected)) === 0); | |
foreach ($expected as $key => $value) { | |
if (is_array($value)) { | |
$this->assertArraySimilar($value, $array[$key]); | |
} else { | |
$this->assertContains($value, $array); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This version is an improvement in that it outputs the same array diff as
assertSame()
for easier debugging. Only ignores key order for first two levels, though.