green123
green123

Reputation: 75

PHP bug in array_udiff()?

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?

Upvotes: 1

Views: 147

Answers (1)

giosh94mhz
giosh94mhz

Reputation: 3116

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.

Upvotes: 3

Related Questions