I’m comparing arrays with array_diff_key and array_diff_ukey but the output is different from both arrays. Manual says there is not difference b/w both function except the later one accpet a callback but I got the difference in output.
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "");
print_r($result = array_diff_key($array1, $array2));
$result = array_diff_ukey($array1, $array2, function($key1, $key2) {
if ($key1 == $key2)
return 0;
elseif ($key1 > $key2)
return 1;
else
return -1;
});
print_r($result);
Output:
Array
(
[a] => green
[2] => red
)
Array
(
[2] => red
)
It’s because you are using the
==operator in your callback. When comparing strings, you should always use===.You can see for yourself by modifying your callback to output the equal keys:
Will result in:
The reason being that when you compare and int vs a string with
==they will both be casted to an int value; so “a” becomes 0.