Skip to content
Advertisement

usort difference php7.1 vs php5.6

I’m currently migrating a project from php5.6 to php7.1. Most is going well, but I just hit a wall on a test.

The function usort doesn’t have the same behavior on both version, and it doesn’t seem to be documented (it’s not that two values are equals and then the order is undefined). In my test case, the returned array order is reversed.

Here is a reproduction of the problem. Note that I return -1 all the time for simplification (I’m focusing in the diff between PHP5.6 and 7 here)

Code run on both versions:

$a = [['value' => 1, 'toto' => 'toto'], ['value' => 1, 'toto' => null]];
usort($a, function ($a, $b) { return -1;});
print_r($a);

Results in PHP 5.6:

Array
(
    [0] => Array
        (
            [value] => 1
            [toto] =>
        )

    [1] => Array
        (
            [value] => 1
            [toto] => toto
        )

)

PHP 7.1

Array
(
    [0] => Array
        (
            [value] => 1
            [toto] => toto
        )

    [1] => Array
        (
            [value] => 1
            [toto] =>
        )

)

Advertisement

Answer

The reason for this is that in this case the values get passed to the usort() callback in different order depending on the PHP version.

https://3v4l.org/bW5WP

$array = ['a', 'b'];
usort($array, function ($firstValue, $secondValue) { echo "COMPARING: {$firstValue} with {$secondValue}n"; return -1;});

PHP 5.6 output:

COMPARING: b with a

PHP 7.x output:

COMPARING: a with b

This doesn’t matter to callbacks which actually compare the given values. Your callback however always returns -1, which means first value is lesser than the second value. In PHP 5.6 this results in b being first in the list, in PHP 7.x a will be first.

Returning incosistent results from the callback will result in undefined behavior if your callback is sorting an array of more than 2 values.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement