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:
$aops = 0;
$x = array(1, 1, 1, -1, -1, -1, 0, 0, 0);
usort($x, function($a, $b) use (&$aops) { $aops++; return $a < $b ? -1 : 1; });
var_dump($aops); // 34
$bops = 0;
$x = array(1, 1, 1, -1, -1, -1, 0, 0, 0);
usort($x, function($a, $b) use (&$bops) { $bops++; return $a === $b ? 0 : ($a < $b ? -1 : 1); });
var_dump($bops); // 17
It's obviously not a problem, though, if all elements of the sorted array are guaranteed to be unique.