PHP Spaceship Operator (<=>)

 ← Dev Articles
👍 0
👎 0

PHP Spaceship Operator (<=>)

 

The PHP Spaceship Operator (<=>) is a comparison operator that provides a three-way comparison between two values. It's also known as the "combined comparison operator."


How it works:

The operator returns -1, 0, or 1 depending on the condition.
-1 => if the left operand is less than the right operand
0 => if both operands are equal
1 => if the left operand is greater than the right operand

 

Sample Usage:

 

 $a = 1;

 $b = 1;

 $result = $a <=> $b; // result is 0

 

 $b = 2;

 $result = $a <=> $b; // result is -1

 

 $b = 0;

 $result = $a <=> $b; // $result is 1

 

 

Spaceship Operator vs using  if-else:

 

 // using if/else

 if ($a < $b) {

    return -1;

 } elseif ($a > $b) {

    return 1;

 } else {

    return 0;

 }

 

 // using spaceship operator

 return $a <=> $b;

 

 

Benefits:
- Concise: Replaces complex if-else chains
- Readable: Clear intention for comparison
- Consistent: Always returns -1, 0, or 1
- Type-safe: Handles different data types predictably