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?

LF00
  • 27,015
  • 29
  • 156
  • 295
  • check the [compare function of array_udiff, similar with array_interset_ukey's compare function](http://stackoverflow.com/a/18093423/6521116) – LF00 May 17 '17 at 10:40

1 Answers1

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

Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295
  • I am getting your point but my exact question is why 0 i.e. false is returned when there is a match –  May 17 '17 at 10:52
  • 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 http://stackoverflow.com/q/43998995/6521116. – LF00 May 17 '17 at 10:57
  • You can print the $k1 and $k2 in the compare funciton to check if the same keys have been compared – LF00 May 17 '17 at 10:58