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