PHP7 is coming! Bring to us… the SPACESHIP Operator

Are you ready for PHP7? We are going to try to help get you ready with a series of short articles describing new features or gotcha’s you need to know about.

What is the spaceship operator (<=>)? It is the newest operator in PHP and PHP’s very first “trirnary” operator. Previously, all other comparison operators in PHP returned either true or false.

In the example above, either $a is greater than $b or it is not, there is no middle ground. $returnValue will contain either true, or it will contain false. The Spaceship Operator changes that. It will return one of 3 values, -1, 0, or 1.

Since there are 3 operators in the Spaceship Operator, and there are 3 values that can be returned, an easy way to look at it is that each operator is assigned a value. The one that is correct – or the one that ‘hits’ – is the value that will be returned.

< = >
-1 0 1

With this in mind now, we can use the spaceship operator to help us to write easier, faster and shorter comparison methods.

For instance, say we want to sort a list of names by length order.

The spaceship operator allows us to get rid of the three IF statements.

With the spaceship operator <=>, here how the compareByLength() function will look like now :

And it is done! Easier to read, faster to code.

The Spaceship Operator is little more than syntactical sugar. As you see above, there are ways to accomplish the same goal in previous versions of PHP. The Spaceship Operator however, will reduce the number of lines of code you need to accomplish that goal. Also, be honest saying “$a SPACESHIP $b” is just fun.

PHP 7 Resources

Jumpstart Training

Get the knowledge you need to ensure your applications are ready to take advantage of the innovations and performance enhancement introduced in PHP7.

Reserve your spot now