The spaceship operator in PHP 7

catgirl

Administrator
Staff member
Administrator
May 28, 2020
155
28
22
United States
envyforums.net
The spaceship operator or <=> is a new operator in PHP 7. It returns 0 if both operands (or sides) are equal, 1 if the left operand is greater, or -1 is the right operand is greater. Compared to using the traditional comparison operators, the spaceship operator shines best in ordering functions which are normally quite large.

Consider the following code:
PHP:
<?php
$numbers = [6,4,1,4,9,2,4,3];

usort($numbers, function($a, $b) {
    return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
});

foreach($numbers as $number) {
    echo "$number\n";
}
It can become as small as:
PHP:
<?php
$numbers = [6,4,1,4,9,2,4,3];

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

foreach($numbers as $number) {
    echo "$number\n";
}

?>
It's much easier to read as well. What do you think about this new operator in PHP 7? Will you use it in your future projects or are you sticking to the traditional operators?