1.2.1420. Usort Sorting In PHP 7.0¶
Usort(), uksort() and uasort() behavior has changed in PHP 7. Values that are equals (based on the user-provided method) may be sorted differently than in PHP 5.
If this sorting is important, it is advised to add extra comparison in the user-function and avoid returning 0 (thus, depending on default implementation). In PHP 5, the results is ::
Array
(
[0] => 3
[1] => 4
[2] => 2
[3] => 6
)
in PHP 7, the result is ::
Array
(
[0] => 2
[1] => 4
[2] => 3
[3] => 6
)
<?php
$a = [ 2, 4, 3, 6];
function noSort($a) { return $a > 5; }
usort($a, 'noSort');
print_r($a);
?>
See also Sort order of equal elements.
1.2.1420.1. Connex PHP features¶
1.2.1420.1.1. Suggestions¶
Make sure the sorting function doesn’t generate any values of the same order.
Add an extra order branch to avoid values of the same order.
Spot the values of the same order after the sort, and sort them again, independently.
1.2.1420.1.2. Specs¶
Short name |
Php/UsortSorting |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Slow (1 hour) |
Changed Behavior |
PHP 7.0 |
Precision |
Medium |
Available in |