PHP Programming
Group for all things PHP, Coding Help, Problems and Solutions
108 Members
Join this group to post and comment.
04 Jan 2019

Do you use PHP Spaceship <=> Operator?

PHP 7 has introduced a new way of evaluating expressions and it's done through a new operator called 'Spaceship Operator'. It's actually quite useful. 

Returns 0 if both sides of the operator are equal
Returns 1 if the left side is greater
Returns -1 if the right side is greater

This comparison works for both integers and for strings. Here's an example.

return 5 <=> 5;  // Will return 0
return 200 <=> 100 // Will return 1
return 100 <=> 200 // Will return -1

For Strings the order of letters in alphabet is ascending in value
Therefore, -
return "a" <=> "b"; // Returns -1
return "y" <=> "x" // Returns 1
return "a" <=> "a" // Returns 0 

Of course, you can even do comparison for array values. Give it a try, you'll enjoy it 👍 

Mohit Patil
Mohit Patil
Computer Science
4mos ago

Still using PHP 5.6 FML 😟 

Zara Astley
Zara Astley
Information Technology
4mos ago

I don't know much about this version.

4mos ago

@Zara Astley - the spaceship operator was introduced in the PHP 7 upgrade.