PHP spaceship operator (<=>) – is it useful?

Since PHP 7, we have brand new (or brand old) operator, called spaceship – how can it be used?Consider this piece of code:

usort($array, function($a, $b) {
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
});

To enhance readability and simplify the sorting process, we can utilize this 🚀 to refactor the previous code. This will eliminate the need for multiple checks and make the code more concise:

usort($array, function($a, $b) { return $a <=> $b; });

Also when talking about object, spaceship operator is a useful tool for simplifying code when comparing multiple properties based on multiple criteria. So we can go from this:

usort($people, function($a, $b) {
if ($a->lastName == $b->lastName) {
if ($a->firstName == $b->firstName) {
return 0;
}
return ($a->firstName < $b->firstName) ? -1 : 1;
}
return ($a->lastName < $b->lastName) ? -1 : 1;
});

To this:

usort($people, function($a, $b) {
return [$a->lastName, $a->firstName] <=> [$b->lastName, $b->firstName];
});

Happy coding!

Leave a Reply