PHP Spaceship Operator (<=>)

June 10, 2022  ‐ 1 min read

One of the new features introduced in PHP 7 was the spaceship operator (<=>). Quite new to PHP but the spaceship operator has been present in other programming languages like Ruby and Perl for a while.

The spaceship operator evaluates to either -1, 0 or 1. Let's consider two operarands a and b being compared by the spaceship operator: a <=> b. This may give the following results:

  • 0 if a and b are equal, thus if a == b is true.
  • 1 if a is greater than b, thus if a > b is true.
  • -1 if a is lower than b, thus if a < b is true.

Pay attention to the fact that the spaceship operator uses loose comparisons. Thus, 1 <=> "1" will result in 0 as well.