3

There seems to be an undocumented change to how PHP 7 handles equal results in usort functions.

$myArray = array(1, 2, 3);
usort($myArray, function($a, $b) { return 0; });
print_r($myArray);

// PHP 5:
Array
(
    [0] => 3
    [1] => 2
    [2] => 1
)

// PHP 7
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

In other words in PHP 7, usort is adding equal values to the end of the array, whereas PHP 5 adds them to the beginning. I can't find any mention of this behaviour.

Is there a way of forcing the PHP 5 behaviour?

3
  • 3
    I don't think usort was ever guaranteed to be stable nor was the sort order of equal elements ever defined. If you relied on the undefined behaviour, you need to change your approach.
    – deceze
    Jun 21, 2016 at 10:24
  • So it was undocumented behaviour in PHP 5, and it still is in PHP 7?
    – Dan Blows
    Jun 21, 2016 at 10:25
  • 4
    @Blowski: It's explicitly documented as undefined.
    – BoltClock
    Jun 21, 2016 at 10:26

1 Answer 1

9

From the PHP docs:

If two members compare as equal, their relative order in the sorted array is undefined.

Relying on undefined behavior is a bad idea. There is no way to change the behavior (apart from making the items not equal).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.