Make sorting stable View as Markdown

Implemented (PHP 8.0)
Authors
Nikita Popov nikic@php.net
Date
2020-05-12
Target
PHP 8.0
Implementation
https://github.com/php/php-src/pull/5236
Source
wiki.php.net/rfc/stable_sorting

Vote

Make sorting in PHP stable? closed
Yes
45
No
0
45 voters
alcaeus Yes 2020-06-04 15:44
bmajdak Yes 2020-06-03 15:29
brzuchal Yes 2020-06-05 12:19
bwoebi Yes 2020-06-03 13:09
carusogabriel Yes 2020-06-07 03:06
colinodell Yes 2020-06-03 13:07
dams Yes 2020-06-03 13:42
daverandom Yes 2020-06-09 17:05
derick Yes 2020-06-03 13:09
dragoonis Yes 2020-06-04 02:02
duodraco Yes 2020-06-03 18:07
ekin Yes 2020-06-08 12:58
galvao Yes 2020-06-03 13:59
geekcom Yes 2020-06-14 19:04
heiglandreas Yes 2020-06-13 14:56
jhdxr Yes 2020-06-04 09:43
kalle Yes 2020-06-03 16:47
kguest Yes 2020-06-04 13:13
klaussilveira Yes 2020-06-16 18:22
kocsismate Yes 2020-06-03 13:17
marandall Yes 2020-06-03 13:21
marcio Yes 2020-06-14 04:00
mariano Yes 2020-06-03 13:21
mcmic Yes 2020-06-03 14:50
mike Yes 2020-06-08 11:38
nicolasgrekas Yes 2020-06-03 13:16
nikic Yes 2020-06-03 13:02
ocramius Yes 2020-06-03 13:16
patrickallaert Yes 2020-06-04 11:14
pierrick Yes 2020-06-03 18:47
pollita Yes 2020-06-04 14:13
rasmus Yes 2020-06-12 21:29
reywob Yes 2020-06-03 13:20
ruudboon Yes 2020-06-11 15:18
santiagolizardo Yes 2020-06-15 17:39
sebastian Yes 2020-06-03 13:17
sergey Yes 2020-06-04 08:05
sirsnyder Yes 2020-06-03 18:09
stas Yes 2020-06-04 05:38
svpernova09 Yes 2020-06-03 13:20
tandre Yes 2020-06-03 13:49
trowski Yes 2020-06-03 20:58
wyrihaximus Yes 2020-06-03 13:12
yunosh Yes 2020-06-04 08:18
zimt Yes 2020-06-11 13:06

Discussions on the mailing list

[RFC] Make sorting stable
by Nikita Popov · 5 messages
[VOTE] Make sorting stable
by Nikita Popov · 2 messages

RFC text

Copied from wiki.php.net, last synchronized Oct 13, 2026 11:51 UTC

Introduction

Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed. This RFC proposes to make all sorts in PHP stable.

If multiple elements in the input array compare equal, they will always be sorted adjacently. However, if the sort is unstable, their relative order is not guaranteed, and will appear to be random. A stable sort guarantees that equal elements will retain the order they had in the original array.

Stable sorts are useful primarily when sorting complex data only by some part of that data. Consider this example:

usort($users, function($user1, $user2) {
    return $user1->age <=> $user2->age;
});

This code sorts users by age. Currently, the order of users in one age bracket will be arbitrary. With a stable sort, the original order of the objects will be retained. For example, if $users was already sorted by name, then $users will now be sorted by age first and name second. Of course, in this case it would be possible to explicitly sort by two criteria:

usort($users, function($user1, $user2) {
    return $user1->age <=> $user2->age
        ?: $user1->name <=> $user2->name;
});

However, this is not always possible, because the criterion by which the data was originally sorted is not explicitly stored. A recent case I ran into was a list of git commits with metadata, which were stored in push order (but the push order was not explicitly stored on each commit).

Apart from user-supplied comparison functions, another case where stable sorting is often desirable is the asort() function, which sorts by value, but preserves keys.

$array = [
    'c' => 1,
    'd' => 1,
    'a' => 0,
    'b' => 0,
];
asort($array);
 
// With stable sorting, the result is always:
['a' => 0, 'b' => 0, 'c' => 1, 'd' => 1]
 
// With unstable sorting, the following results are also possible:
['b' => 0, 'a' => 0, 'c' => 1, 'd' => 1]
['a' => 0, 'b' => 0, 'd' => 1, 'c' => 1]
['b' => 0, 'a' => 0, 'd' => 1, 'c' => 1]

It is possible to emulate a stable sort on top of an unstable one by explicitly storing the original order of the elements and using it as a fallback comparison criterion. For example, a stable sort implementation could look like this:

function stable_usort(array &$array, callable $compare) {
    $arrayAndPos = [];
    $pos = 0;
    foreach ($array as $value) {
        $arrayAndPos[] = [$value, $pos++];
    }
    usort($arrayAndPos, function($a, $b) use($compare) {
        return $compare($a[0], $b[0]) ?: $a[1] <=> $b[1];
    });
    $array = [];
    foreach ($arrayAndPos as $elem) {
        $array[] = $elem[0];
    }
}

While this approach works, it is also highly inefficient. The additional indirection makes sorting much slower, and will also skyrocket memory usage during sorting.

Proposal

This RFC proposes to make all PHP sorting functions stable. This includes sort, rsort, usort, asort, arsort, uasort, ksort, krsort, uksort, array_multisort, as well as corresponding methods on ArrayObject.

Implementation

The underlying sort implementation zend_sort remains an unstable hybrid quick sort. Stability is achieved by storing the original order of the array elements and using that order as a fallback sorting criterion.

This matches what is implemented in the stable_usort PHP code above, with the difference that certain internal implementation details allow us to do this highly efficiently, without increasing memory usage.

An alternative would be to change the underlying sorting algorithm to Timsort, which is inherently stable.

Illegal comparison functions

PHP documents that comparison functions must return an integer smaller than, equal to, or greater than zero. However, due to the specific implementation of sorting in PHP, it is currently also possible to return a boolean that indicates whether the value is greater:

usort($values, function($a, $b) {
    // Should be $a <=> $b !
    return $a > $b;
});

This works, because PHP currently only checks whether the comparison result is “greater than” or not, and never explicitly distinguishes the “equal” and “smaller than” cases. This breaks down with the approach proposed here, because we now do need to know whether values are equal or not, in order to use the fallback sorting criterion.

This RFC takes two steps to address this. First, a deprecation warning will be emitted if a boolean is returned from a custom comparison function. The deprecation warning is thrown only once per sort:

usort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero

Second, if boolean false is returned, PHP will automatically call the comparison function again with arguments swapped. This allows us to distinguish whether the “false” stood for “equal” or “smaller than”. This fallback behavior should be removed in a future version of PHP.

Performance

Of course, stable sorting is not entirely free. This gist contains a simple script to evaluate sort performance at various levels of duplication in the array. As the results show, sort performance is essentially unchanged if the array does not contain duplicates (and thus stable vs unstable sorting does not matter). However, if the array contains many duplicates, the unstable sort becomes faster, while the stable sort always has approximately the same performance.

Backward Incompatible Changes

As described in the “Illegal comparison functions” section, comparison functions returning booleans instead of integers are deprecated and will no longer be supported in the future.

Tests that rely on the current sorting order may need to be adjusted. It should be noted that the impact is expected to be smaller than for the PHP 7.0 sorting order changes, because this time the order for small arrays (up to 16 elements) is not affected. These are also the ones that are more common in tests.

Vote

Voting started 2020-06-03 and ends 2020-06-17.

Vote: Make sorting in PHP stable? — Yes: 45 · No: 0 (closed)