I’m trying to simplify a contrived callback function in PHP for sorting.
function my_sort($a, $b) {
if($a == $b) return 0;
return $a < $b ? 1 : -1;
}
According to the PHP documentation on usort, the order is undefined when you return equal.
Does this mean that I can skip testing for equality altogether?
function my_sort($a, $b) {
return $a < $b ? 1 : -1;
}
As @lanzz said, writing sort function that way will make it less efficient. Equal elements will be considered not-equal (= that should be reordered), hence the number of the sorting function’s calls will be higher.
For example:
It’s obviously not a problem, though, if all elements of the sorted array are guaranteed to be unique.