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:
0ifaandbare equal, thus ifa == bistrue.1ifais greater thanb, thus ifa > bistrue.-1ifais lower thanb, thus ifa < bistrue.
Pay attention to the fact that the spaceship operator uses loose comparisons. Thus, 1 <=> "1" will result in 0 as well.