Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

php - Misunderstanding the behavior of array_udiff

I am having troubles to understand how array_udiff works.

According to the documentation:

array_udiff ($array1, $array2, data_compare_func)

[...] data_compare_func 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.

So considering this function:

function please_compare($a, $b) {
  return $a !== $b;
};

if $a equals $b, the method will return 0, 1 otherwise (because of this).

(There is no -1 returned here and I have the feeling that the explanation comes from there but I can just compare that the values are different, not that one is greater than the other one.)

Could someone explain me array_udiff's behavior in the following snippet? I also included the output of array_diff, which is actually the behavior I was expecting?

$array1 = array('a', 'b', 'c', 'd');
$array2 = array('a', 'b', 'c');

print_r(array_udiff($array1, $array2, 'please_compare'));
/* Returns:
     Array
     (
       [0] => a
       [1] => b
       [3] => d
     )
*/

print_r(array_diff($array1, $array2));
/* Returns:
     Array
     (
       [3] => d
     )
*/
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

array_udiff relies on the comparison function returning appropriate values, because it ranks the elements of your arrays. If you add some output to your comparison function, you will see that array_udiff first determines the sort order for both arrays, and only after it has done this does it start comparing array1 elements to array2 elements. By returning 1 from your comparison function, you are telling array_udiff that 'a' > 'b' and 'b' > 'a', and similarly for all other elements in both arrays. In your particular case, this causes array_udiff to think that everything in array1 > everything in array2, until it finally happens to compare the 'c' in array1 to the 'c' in array2, and gets 0 back from your function (this is why it left 'c' out of the result). See this PHP fiddle for a demonstration of the internal working of array_udiff.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...