Everyone knows that PHP is a poorly designed language.
As far back as version 4.1.0, they changed their sort from stable to unstable. A stable sort keeps elements that are “equal” in the same relative order. This is useful for example: for sorting by “name” and then “age”.
The reason for this change was probably to use less memory, because a stable sort in n log n time cannot be sorted in place. But they should have made it an option to switch back to the stable sort.
In fact, there is a bug ticket request that it be switched back to the stable sort.
Amusingly, it was “denied on the grounds that there is no efficient implementation for that.”
Speaking of “efficient implementation”, let’s take a look at the comparison function in the example in the manual.
http://us2.php.net/manual/en/function.usort.php
function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; }
This can be shortened to:
function cmp($a, $b) { return $a - $b; }
because only numbers are being compared. If you were comparing strings it would probably be better to use strcmp.
Related posts:








Actually, lack of a built-in stable sort would make a whole lot of other great languages suck too, like C for starters. That said, I agree it would be much better if there were some option to use a stable sort, even if it were less efficient, because sometimes stable really is what you need.
Regarding the comparison function example, you neglect to mention that your simplified example of $a – $b returns different results than their example function. For starters, yours will return an integer (any integer) and theirs always returns 0, 1, or -1 as a well-behaved comparison function should. Another possible difference is that their use of an == comparison takes advantage of type juggling if applicable to do the comparison in a standard PHP way. Simply using the subtraction operator would potentially get different results where two values might both convert to 0 numerically but are not equal according to ==.
You’re right about the importance of input values though – if the comparison function needs to handle arbitrary data types, or even arbitrary scalar data types, it would need to be more robust, whether or not it was more efficient.