1
function value_compare_func($a, $b){
    if ($a === 'n_3') {
        return 0;
    }
    return 1;
}
$array1 = array("n_1", "n_2", "n_3", "n_4" );
$array2 = array("green");
$result = array_udiff($array1, $array2, "value_compare_func");
print_r($result);

The expected output is:

Array([0] => 'n_1', [1] => 'n_2' , [3] => 'n_4' )

But PHP outputs:

Array([1] => 'n_2' , [3] => 'n_4' )

Where is n_1?

4
  • 2
    Interesting differences: HHVM seems to confirm what looks right, while PHP7 differs quite distinctly from PHP5 - perhaps you should consider raising a bug through the appropriate channels rather than simply pointing it out here on SO Commented Oct 20, 2015 at 22:41
  • @MarkBaker Actually, the only difference between different versions of PHP and HHVM is that they iterate through the values in a different order. If the function were used correctly I'm sure the output would be the same: 3v4l.org/f5pS9 Commented Oct 20, 2015 at 23:06
  • However, looking at the output above, it appears that only HHVM is actually efficient in that it only compares the necessary values once. All versions of PHP seem to compare the same values in $a multiple times. Maybe that would be an actual bug report. Commented Oct 20, 2015 at 23:15
  • I've send it to php developers and will inform you when they answer Commented Oct 21, 2015 at 21:17

1 Answer 1

3

This is not a bug since you are not using the function as described in the docs.

The compare callback MUST compare $a and $b and decide if they are equals, to calculate the difference. The docs also states that you MUST return -1 and 1 to hint whether $a comes before $b; this may sound useless, but is probably used internally.

Your callback translate to something like: "every element comes after every other element, except when the first element is equal to 'n_3' in which case is equal to every other element". Well, it doesn't make sense, just like the result you get.

If you want to remove all element equals to 'n_3', just use array_filter. If you want to compare an array difference, then define a compare callback.

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

1 Comment

I can confirm that returning always 1 or 0 is wrong. I made the same mistake, and everything started to work when I modified the function to return a real order.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.