PHP Spaceship Operator Explained
This article provides a clear overview of the PHP spaceship operator
(<=>), which was introduced in PHP 7. You will learn
how this three-way comparison operator works, what values it returns,
and how to use it to write cleaner, more efficient sorting logic in your
PHP applications.
The spaceship operator (<=>) is used to compare
two expressions. Instead of returning a simple true or false boolean
value, it returns one of three integers based on the outcome of the
comparison: -1, 0, or 1.
How It Works
The operator compares the left-hand operand (\(a) to the right-hand operand (\)b) and behaves as follows:
- Returns
0if $a is equal to \(b (\)a == $b) - Returns
-1if $a is less than \(b (\)a < $b) - Returns
1if $a is greater than \(b (\)a > $b)
Here is a basic code example demonstrating these three outcomes:
// Integers
echo 1 <=> 1; // Outputs: 0 (1 is equal to 1)
echo 1 <=> 2; // Outputs: -1 (1 is less than 2)
echo 2 <=> 1; // Outputs: 1 (2 is greater than 1)
// Strings (compared alphabetically)
echo "a" <=> "a"; // Outputs: 0
echo "a" <=> "b"; // Outputs: -1
echo "b" <=> "a"; // Outputs: 1Practical Use Case: Custom Sorting
The primary benefit of the spaceship operator is in sorting functions
like usort(), uasort(), or
uksort(). These functions require a callback that returns
-1, 0, or 1 to determine the
order of elements.
Before PHP 7, sorting required a verbose conditional statement:
// The old way
usort($array, function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
});With the spaceship operator, this entire logic can be condensed into a single line:
// The modern way
usort($array, function($a, $b) {
return $a <=> $b;
});This operator works with integers, floats, strings, arrays, and objects, making it a highly versatile tool for data comparison in PHP.