Search code examples
phparraysfilterassociative-arrayarray-difference

array_diff() is removing a value which is clearly different at the same key in the second array, but the same value is found at a different key


I have 2 identical PHP arrays. There is only one value different. I want to find this value:

var_dump(array_diff(array(
  "a" => "1",
  "b" => "SomeString",
  "c" => 1, // <- different value, same key 
  "d" => "4521",
  "e" => "7546654241",
  "f" => "78",
  "g" => "99.999",
  "h" => "34",
  "i" => "http://google.com/"
), array(
  "a" => "1",
  "b" => "SomeString",
  "c" => "0", // <- different value, same key 
  "d" => "4521",
  "e" => "7546654241",
  "f" => "78",
  "g" => "99.999",
  "h" => "34",
  "i" => "http://google.com/"
)));

The result is array(0) { } but there should be new "c" value but isn't. When I remove all others values:

var_dump(array_diff(array(
  "c" => 1
), array(
  "c" => "0"
)));

I get what I want array(1) { ["c"]=> int(1) }.

I don't understand it. Why is it so?


Solution

  • array_diff() matches values from the first array to the second

    returns the values in array1 that are not present in any of the other arrays.

    The value 1 for key c in the first array does exist in the second array as the value for key a, so there is no difference there that array_diff() will recognise

    Perhaps using array_diff_assoc() will gve you the result that you're actually trying to get.... http://ideone.com/xHCVfF