What is the spaceship operator in PHP?
20 August 2024 (Updated 18 May 2025)
The spaceship operator is used to compare two values and return an integer based on the comparison result. It’s typically used when implementing a custom sort function.
For example, given the below code:
$result = $a <=> $b;
$result will be:
-1if the left-hand operand ($a) is less than the right-hand operand ($b).- 0 if
$aand$bare equal. 1if$bis greater than$a.
The above code is equivalent to:
if ($a < $b) {
return -1;
} elseif ($a == $b) {
return 0;
} else {
return 1;
}
Tagged:
PHP