What is the "spaceship operator" of PHP7?

17

I was checking out the New Features of PHP 7 and I came across an operator, which I had never seen in any programming language. The PHP Manual has demon- strated it from Spaceship Operator .

I'll show you what I've seen below:

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

I do not know if I understood correctly, but it seems to me that it does the same thing as strcmp .

  • After all, what is the purpose of this operator simplified?
  • What are the benefits of using it?
asked by anonymous 16.09.2015 / 17:48

4 answers

21

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

  • Returns 0 if the values on both sides are equal .
  • Returns 1 if the value to left is greater.
  • Returns -1 if the value to 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 function strcmp is limited to strings .

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

    
16.09.2015 / 18:04
8

The documentation already says well what it is:

  

The spaceship operator is used to compare two expressions. It returns an integer smaller than, equal to, or greater than zero when $ a is respectively less than, equal to, or greater than $ b. Comparisons are performed according to the usual PHP type comparison rules.

Improving the documentation example:

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

The main advantage is to be type independent.

    
16.09.2015 / 18:05
5

In general, languages use a function. The function you quoted compares strings , since the <=> operator works with several types where this type of comparison is possible.

Before PHP even had a function that did this with numbers.

    
16.09.2015 / 18:05
5

From a version here, php seems to be trading some functions for operators. For example, pow () that does the exponentiation calculation can be replaced with ( ** ); func_get_args () can be exchanged for Spread Operator . These two are available from php 5.6 .

The spacecraft does almost the same thing as the strcmp function, however it applies to others types, not just strings.

    
16.09.2015 / 18:10