PHP Spaceship Operator (<=>)
The spaceship operator (<=>) was introduced in PHP 7. It is a three-way comparison operator that returns an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b.
1. How it Works
The operator returns:
-1if the left operand is less than the right.0if both operands are equal.1if the left operand is greater than the right.
It can be used to compare integers, floats, and strings.
2. Examples
Integers
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
Strings
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
3. Use Case: Sorting
The spaceship operator is particularly useful for writing sorting callbacks, for example with usort().
$numbers = [3, 1, 4, 1, 5, 9];
usort($numbers, function ($a, $b) {
return $a <=> $b;
});
print_r($numbers);
// Array ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 [5] => 9 )