Close

July 22, 2016

The Thing About PHP 7’s Spaceship Operator

Subscribe So You Never Miss An Episode

[saf]

May the force be with you… 😉

Unless you’ve been under a rock (which is totally cool if so) you know PHP 7 has been out for a bit now. I finally took some time the other day to fire it up on one of my dev servers and see what all the fuss is about.

Online, I’d kept hearing about this “spaceship” operator.

This thing’s kind of cool actually. Let me show you.

So, here’s a common bit of code you might see pre-PHP7:

rp1

This is a sorting routine.

usort() lets you sort an array using a user-defined comparison function… in this case compare_length(). So, what this does is re-arrange the $names array to be in order of the length of the names in it. Here’s the output:

rp2

Ok, simple enough.

But, notice the big compare_length() function. It works fine, but that’s a good chunk of code just to run a simple comparison. And, this is where the spaceship operator comes in. Here’s what the function looks like with PHP 7:

rp3

Just three lines now. Pretty sweet!

So, how does the spaceship operator (<=>) work?

You can use it just like you might any other operator. For example, equals:

1 == 1;

Except it looks like this in spaceship mode:

1 <=> 1;

When you do that, PHP will run a “trinary” comparison. So, it’ll check to see if 1 is less than, equal to or greater than 1. Thus the syntax of a less than sign (<), an equal sign (=) and a greater than sign (>): <=>.

And here’s what it’ll return…

If $a is less than $b, it returns -1. If $a is equal to $b, it returns 0. And, if $a is greater than $b, it returns 1. Here’s an example:

rp4

Slicky ricky, eh?

Anyhoo, thought I’d give you the low down on it. You’re welcome! 😉

If you want to learn even more PHP so you can still cram your skull with Cheetos and binge watch Star Wars movies without having to deal with that annoying boss, then get your butt over to: http://www.johnmorrisonline.com/learnphp and take my free PHP course.

P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, source code and exclusive courses on Patreon.


Also published on Medium.