I am having troubles to understand how array_udiff
works.
According to the documentation:
array_udiff ($array1, $array2, data_compare_func)
[...]
data_compare_func
function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
So considering this function:
function please_compare($a, $b) {
return $a !== $b;
};
if $a equals $b, the method will return 0, 1 otherwise (because of this).
(There is no -1 returned here and I have the feeling that the explanation comes from there but I can just compare that the values are different, not that one is greater than the other one.)
Could someone explain me array_udiff
's behavior in the following snippet? I also included the output of array_diff
, which is actually the behavior I was expecting?
$array1 = array('a', 'b', 'c', 'd');
$array2 = array('a', 'b', 'c');
print_r(array_udiff($array1, $array2, 'please_compare'));
/* Returns:
Array
(
[0] => a
[1] => b
[3] => d
)
*/
print_r(array_diff($array1, $array2));
/* Returns:
Array
(
[3] => d
)
*/
array_udiff
relies on the comparison function returning appropriate values, because it ranks the elements of your arrays. If you add some output to your comparison function, you will see that array_udiff
first determines the sort order for both arrays, and only after it has done this does it start comparing array1 elements to array2 elements. By returning 1 from your comparison function, you are telling array_udiff
that 'a' > 'b' and 'b' > 'a', and similarly for all other elements in both arrays. In your particular case, this causes array_udiff
to think that everything in array1 > everything in array2, until it finally happens to compare the 'c' in array1 to the 'c' in array2, and gets 0 back from your function (this is why it left 'c' out of the result).