Search code examples
phparrayscomparisonintersectioncustom-function

Why does array_uintersect_assoc() need the comparison function to return non-boolean values?


I wondered why array_uintersect_assoc()'s custom comparison 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

When I compare two arrays, I only need a boolean return value: the elements either match or they don't.

What's the actual reason of this behavior?


Solution

  • The function has been implemented this way to allow the usage of "classical" comparison functions which use such a return strategy. Such a function typically needs to be able to express three cases which is not possible with a boolean return value, for obvious reasons.

    You can, however, also use a comparison function which does return a boolean result, since php as a weak typed language will automatically convert that for you. Take a look at that example which is a slightly modifed version of the one given in the function documentation:

    <?php
    function mystrcasecmp($a, $b) {
        return strcasecmp($a, $b) ? true : false;
    }
    
    $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
    $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");
    
    print_r(array_uintersect_assoc($array1, $array2, "mystrcasecmp"));
    

    You can see that the comparison function used here returns a boolean, yet the result is exactly the same.

    Bottom line: the existing implementation is more flexible, whilst allowing for the use of a comparison function returning a boolean result too.