phpunit-testingphpunitassert

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


What is a good way to assert that two arrays of objects are equal, when the order of the elements in the array is unimportant, or even subject to change?


Solution

  • The cleanest way to do this would be to extend phpunit with a new assertion method. But here's an idea for a simpler way for now. Untested code, please verify:

    Somewhere in your app:

     /**
     * Determine if two associative arrays are similar
     *
     * Both arrays must have the same indexes with identical values
     * without respect to key ordering 
     * 
     * @param array $a
     * @param array $b
     * @return bool
     */
    function arrays_are_similar($a, $b) {
      // if the indexes don't match, return immediately
      if (count(array_diff_assoc($a, $b))) {
        return false;
      }
      // we know that the indexes, but maybe not values, match.
      // compare the values between the two arrays
      foreach($a as $k => $v) {
        if ($v !== $b[$k]) {
          return false;
        }
      }
      // we have identical indexes, and no unequal values
      return true;
    }
    

    In your test:

    $this->assertTrue(arrays_are_similar($foo, $bar));