2

I have two arrays, I would like to compare.

array1:

array(4) {
  ["123"]=>
  array(5) {
    ["animal"]=>
    string(2) "cat"
    ["name"]=>
    string(4) "fred"
  }
  ["345"]=>
  array(5) {
    ["animal"]=>
    string(3) "dog"
    ["name"]=>
    string(4) "alan"
  }
  ["order"]=>
  string(2) "12"
}

array2:

   array(4) {
      ["123"]=>
      array(5) {
        ["animal"]=>
        string(2) "cat"
        ["name"]=>
        string(4) "fred"
      }
      ["345"]=>
      array(5) {
        ["animal"]=>
        string(3) "fox"
        ["name"]=>
        string(4) "tom"
      }
      ["order"]=>
      string(2) "12"
    }

I compare them with array_diff:

$result = array_diff($array1, $array2);

But if I var_dump $result, I get the following output:

array(0) {
}

Does anyone have an idea why?

peace_love
  • 6,229
  • 11
  • 69
  • 157

2 Answers2

0

For associative arrays you should use array_diff_assoc. Also see the user contributed notes for how to do this recursively, if you need to.

Kenney
  • 9,003
  • 15
  • 21
  • I already tried this `$result = array_diff_assoc($array1, $array2);` but still I get the output `array(0) { }` – peace_love Nov 29 '15 at 13:53
0

With the help of sinaza I found out that no difference was displayed, because array_diff works different with multidimensional arrays.

Here is the code, that worked for me:

foreach ($array1 as $k1 => $v1) {
   if (array_diff($array2[$k1], $array1[$k1])){
      $result[$k1] = array_diff($array2[$k1], $array1[$k1]);
   }
}
peace_love
  • 6,229
  • 11
  • 69
  • 157