How To

PHP Spaceship

We built this operator on PHP.

It’s no Jefferson Starship, but in PHP 7 there’s an awesome new comparison operator called ‘Spaceship.’

Dragon Fly Dragon Fly

Operators are those things we use to tell PHP what ‘operations’ to perform on variables and values. Comparison operators are used to compare two values (like a number or string). And Spaceship — <=> — is a cool new one.

It’s a combined comparison operator and returns:

  • 0 if values on either side are equal
  • 1 if value on the left is greater
  • -1 if the value on the right is greater

Top ↑

Red Octopus Red Octopus

So why would anyone use it?

Let’s say you have an array of characters with lists of when they died. But the characters are ordered alphabetically. Sara Lance comes after Lexa, even though Sara died first. And let’s say you want to take the list of all the characters who died and put them in the order of death, not their names.

To do this in PHP, you would use usort or uasort to ‘user sort’ the array. The A in the sort is if you have an associative array, and you want to keep ‘name’ and ‘date of death’ connected when you sort. Which you do.

Top ↑

Spitfire Spitfire

In PHP 5, the sort would look like this:

uasort( $death_list_array, function($a, $b) {
	$return = '0';
	if ( $a['died'] &lt; $b['died'] ) $return = '-1';
	if ( $a['died'] &gt; $b['died'] ) $return = '1';
	return $return;

Which isn’t bad, but it’s messy right?

Top ↑

Earth Earth

In PHP 7, the sort would look like this:

uasort( $death_list_array, function($a, $b) {
	$return = $a['died'] &lt;=&gt; $b['died'];
	return $return;

Way nicer, and faster, isn’t it?

Top ↑

Freedom at Point Zero Freedom at Point Zero

Why not use it all the time? Because it’s PHP 7+ only, and for some reason not all servers have PHP 7 as the command line version of PHP. Which means if you use it, sometimes wp-cli commands don’t run.

However. If you have PHP 7 all across the board, then use the starship and save yourself some flying time.