Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2018 by Frank Perez.

PHP Spaceship Operator

One of the new features to hit PHP 7 is the Spaceship Operator. This new trick helps improve the way you’d compare 2 expressions. In short, the comparison returns 1 of 3 values (-1, 0, or 1) depending on the result of the comparison.

Let’s look at a few examples below.

The following comparisons each return 0, meaning both values are equal.

<?php

echo 1 <=> 1;
echo 1.5 <=> 1.5;
echo "a" <=> "a";

Here are some examples of comparisons that would return -1. You’ll see that the first value is less than the second value.

<?php

echo 1 <=> 2;
echo 1.5 <=> 2.5;
echo "a" <=> "b";

Lastly, we have some examples where the first value is greater than the second value generating a positive 1 value.

<?php

echo 2 <=> 1;
echo 2.5 <=> 1.5;
echo "b" <=> "a";

Example Usage

Let’s assume we have a list of products, and want to sort each product by price descending.

First we’ll create a Product class to hold our product information.

<?php

class Product
{
    private $name;
    private $price;

    public function __construct(string $name, float $price)
    {
        $this->name = $name;
        $this->price = $price;
    }

    public function name() : string
    {
        return $this->name;
    }

    public function price() : float
    {
        return $this->price;
    }
}

Next, let’s create an array of new products.

<?php

$products = [
    new Product('Test Product 1', 9.99),
    new Product('Test Product 2', 19.99),
    new Product('Test Product 3', 1.99),
    new Product('Test Product 4', 5.99),
];

Now let’s say we want to sort this array by each price descending. We can do this by using the usort function, and by passing it an anonymous function to handle the sorting logic.

<?php

usort($products, function($product1, $product2) {
    return $product2->price() <=> $product1->price();
});

If we want to sort it instead by price ascending, then we can simply flip the order of how we’re comparing $product1 and $product2.

<?php

usort($products, function($product1, $product2) {
    return $product1->price() <=> $product2->price();
});

We can use this same logic to sort really by any parameter/attribute for each product.