About array_udiff, I want to ask again

2 days ago I asked this question ( I am confused about the problem of how to use array_udiff ).
I apologize to discuss this issue again.
Although I have a solution to the problem, but I'm still confused on this issue:
demo1:

function myfunction($v1,$v2) { if ($v1===$v2) { return 0; } return 1; } $a1=array("a"=>"Cat","b"=>"Dog","c"=>"Horse"); $a2=array(1=>"Cat",2=>"Dog",3=>"Fish"); print_r(array_udiff($a1,$a2,"myfunction")); 

output:

 Array ( [c] => Horse ) 

demo2:

 function myfunction($v1,$v2) { if ($v1===$v2) { return 0; } return 1; } $a1 = array(1,2,3,4,5); $a2 = array(1,6,3,4,5); print_r(array_udiff($a1,$a2,"myfunction")); 

I expect this to return:

 Array ( [0] => 2 ) 

but conclusion:

 Array ( [0] => 1 [1] => 2 [2] => 3 [4] => 5 ) 

Yes, I know, I need according to the php manual,
demo3:

 function myfunction($v1,$v2) { if ($v1 < $v2) { return -1; } elseif ($v1 > $v2) { return 1; } else { return 0; } } $a1 = array(1,2,3,4,5); $a2 = array(1,6,3,4,5); print_r(array_udiff($a1,$a2,"myfunction")); 

output:

 Array ( [1] => 2 )// it right 

What I'm confused about is that demo1 is fine.

+6
source share
1 answer

The result you get is that you use a callback that returns 1 and 0 . Although logically this is justified (i.e. 1 means "equal" and 0 means "not equal") - PHP expects a callback that returns a full comparison - thus, not only for equality, but also more and less comparison.

To understand why this is the case, you need to understand how PHP handles calculating difference arrays. This is not just going through both arrays. PHP first sorts the arrays, then performs the checks. This is because a simple walk (nested loop) will lead to complexity O(n*m) , while sorting arrays first will lead to complexity O(k log(k)), k=max(n, m) for two arrays of size n and m . And for sorting elements through a custom callback, this is not enough to verify the equality of elements. You will need to know their order, so a smaller / larger comparison is required.

So, as a conclusion: you can use the callback only with full -1/0/1 values ​​as a result. If your callback returns something else, the results will be unpredictable - why they might be “right” and “wrong” for different inputs.

+6
source

All Articles