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.

1

2

3

4

5

6

<?php

echo1<=>1;

echo1.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.

1

2

3

4

5

6

<?php

echo1<=>2;

echo1.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.

1

2

3

4

5

6

<?php

echo2<=>1;

echo2.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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?php

classProduct

{

private$name;

private$price;

publicfunction__construct(string$name,float$price)

{

$this->name=$name;

$this->price=$price;

}

publicfunctionname():string

{

return$this->name;

}

publicfunctionprice():float

{

return$this->price;

}

}

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

1

2

3

4

5

6

7

8

9

<?php

$products=[

newProduct('Test Product 1',9.99),

newProduct('Test Product 2',19.99),

newProduct('Test Product 3',1.99),

newProduct('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.

1

2

3

4

5

6

<?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.

1

2

3

4

5

6

<?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.

Tags

About This Blog

I'm writing this blog in order to share what I'm learning with the world. Since you learn best by teaching others and writing things down, I figured this would be the best way to really tackle any new technologies I plan on learning. I hope this blog will help you as much as it will benefit me.