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.

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

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

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.

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

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.

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.

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