2

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I am getting your point but my exact question is why 0 i.e. false is returned when there is a match
For there are some comparation of the keys in the two array will be saved. not all the keys in the first array will be compared to the second array. You can check stackoverflow.com/q/43998995/6521116.
You can print the $k1 and $k2 in the compare funciton to check if the same keys have been compared

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.