phparraysmultidimensional-arraycomparisonarray-difference

Two 2d arrays loosely evaluated as unequal despite having the same data in differently ordered rows


When comparing arrays The Documentation says

$a == $b Equality TRUE if $a and $b have the same key/value pairs.

Though when comparing with multidimensional arrays this doesn’t seem to be the case

$a = array(
  array("test"),
  array("testing"),
);
$b = array(
  array("testing"),
  array("test"),
);

var_dump($a);
var_dump($b);
var_dump($a == $b);

returns

array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(4) "test"
  }
  [1] =>
  array(1) {
    [0] =>
    string(7) "testing"
  }
}
array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "testing"
  }
  [1] =>
  array(1) {
    [0] =>
    string(4) "test"
  }
}
bool(false)

Same arrays, Different order. array_diff() returns correctly though.

Is this an expected feature ? I know I can compare with array_diff($a,$b) + array($b, $a). I'm not sure why the == doesnt work though.


Solution

  • This is because your arrays are different in the leaf nodes.

    In your first array 0 = test and in your second array 0 = testing.