2
votes

In the following PHP program:

<?php
    $array1=['a'=>'brown','b'=>'green','c'=>'yellow','d'=>'blue','e'=>'magenta'];
    $array2=['f'=>'black','g'=>'white','b'=>'violet','c'=>'pink'];

    function my_function($k1,$k2){
        if($k1===$k2)
            return 0;
        return($k1>$k2)?1:-1;
    }

    $result=array_intersect_ukey($array1,$array2,'my_function');
    print_r($result);
?>

Output:

Array ( [b] => green [c] => yellow )

Question 1:

I believe that return 0 means false, and returning anything other than 0 is true. So, basically this program returns false when keys match and true when keys don't match. But it should exactly be the opposite. Why is this?

Question 2:

Comparing whether two keys are equal is all right. But how can we find the greater one and lesser one between two keys in string format. Is the ASCII value is being checked for?

1

1 Answers

1
votes

From the note of the php manual.

"array_intersect_ukey" will not work if $key_compare_func is using regular expression to perform comparison. "_array_intersect_ukey" fully implements the "array_intersect_ukey" interface and handles properly boolean comparison. However, the native implementation should be preferred for efficiency reasons.

For example, when compare [1,2,5] and [3,5,7], in order to not compare all the values, php save some extra comparation by using the sorted elements's order. So you have to implement big, less, and equal of the compare function.

You can also refer to my post about array_udiff's compare function and the answer for a good insight.

For your question 2, you can compare the ascii value. for php7 just use return $k1 <=> $k2; is ok