Explain the spaceship operator in PHP.

Beginner

Answer

The spaceship operator <=> (introduced in PHP 7.0) is a three-way comparison operator that returns:

  • -1 if left operand is less than right
  • 0 if operands are equal
  • 1 if left operand is greater than right
echo 1 <=> 2;  // -1
echo 2 <=> 2;  // 0
echo 3 <=> 2;  // 1

It's particularly useful for sorting callbacks and comparing multiple values.