0

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 array, 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). Im not sure why the == doesnt work though

Overflowh
  • 1,103
  • 6
  • 18
  • 40
exussum
  • 18,275
  • 8
  • 32
  • 65
  • 1
    Because of the integer keys. Your array is basically `array( 0 => array("test"), 1 => array("testing"))` and `array( 0 => array("testing"), 1 => array("test") );` - which are not the same. – ʰᵈˑ Mar 18 '15 at 09:24
  • Argh completely overlooked that, If you make that an answer ill accept it – exussum Mar 18 '15 at 09:28

3 Answers3

1

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

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

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
0

Use === comparison for taking care about keys order.

Check this source:

Compare multidimensional arrays in PHP

regards

Community
  • 1
  • 1
manuelbcd
  • 3,106
  • 1
  • 26
  • 39
0

== sign allows for comparison of arrays in any order, it will internally use a sort on the master array and do the === comparision.

However it does not do a sort on the sub-arrays, you will need to do that manually before the comparison

NOTE : see == & === difference details here

Community
  • 1
  • 1
arkoak
  • 2,437
  • 21
  • 35