/ php

PHP 7 - Spaceship Operator

The spaceship operator ( <=> ) is new in PHP 7.0. You may hear it being referred to as the "Combined Comparison Operator" and sometimes the "rocket" or "rocketship" operator as it also looks like a rocket on its side.

Simply put, it will return a -1, 0, or 1 depending on whether the item on the left is less-than, equal to, or greater than the item on the right. For a full breakdown of the comparisons against different types, then check here, but it's fairly obvious.

Ideal Use Case

This operator is perfect for custom sort functions with usort, uksort, and uasort. For example, if I wanted to write a custom sort function before this came along, I would write something like:

$sorter = function($a, $b) {
    if ($a < $b)
    {
        $result = -1;
    }
    elseif ($b < $a)
    {
        $result = 1;
    }
    else
    {
        $result = 0;
    }
    
    return $result;
};

$myArray = array(5,6,2,7,4,8,1,3);
usort($myArray, $sorter);
print_r($myArray); // array(1, 2, 3, 4, 5, 6, 7, 8)

Now the sorter object can now be created with a single line:

$sorter = function($a, $b) { return $a <=> $b; };
$myArray = array(5,6,2,7,4,8,1,3);
usort($myArray, $sorter);
print_r($myArray); // array(1, 2, 3, 4, 5, 6, 7, 8)

The other benefit is consistency. Before this, half of my sort functions started with $a > $b returning 1 and the other half having it the other way around and I would either flip any combination of the signs, the values, or the variables, or reverse the array after the sort until I got the desired effect. Now I will keep it exactly the same and just multiply $result by -1 if I want the reverse order. Just remember that in the most basic form of $a <=> $b, assuming parameters are ($a, $b) you will get an ascending order.

Stuart Page

Stuart Page

Stuart is a software developer with a passion for Linux and open source projects.

Read More