What are the PHP7 "spaceship operator" <=> for?

Question:

I was taking a look at PHP 7's New Features and I came across an operator, which I had never seen in any programming language. The PHP Manual called it Spaceship Operator .

I'll demonstrate what I saw below:

echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

I don't know if I got it right, but it seems to me that it does the same thing as strcmp .

  • After all, simply, what is the purpose of this operator?
  • What are the advantages obtained from using it?

Answer:

The <=> operator is used to make combined comparisons.

  • Returns 0 if values ​​on both sides are equal .
  • Returns 1 if the value on the left is greater.
  • Returns -1 if the value on the right is greater.

Example:

echo 1 <=> 1; // 0
echo 3 <=> 4; // -1
echo 4 <=> 3; // 1

The advantage of using the <=> operator is that it is not restricted to a particular type, whereas the strcmp function is limited to strings .

In languages ​​like Ruby , Perl and Groovy this operator is also present.

Scroll to Top