DEV Community

Parixit Patel
Parixit Patel

Posted on

PHP 7 - Two useful operators, You Need to Know

Spaceship operator:

We all are using comparison operators like greater than (>), less than (<), greater than equals(>=), less than equals (<=), etc. These operators are very useful in daily programming tasks.

In PHP 7, We have one more comparison operator Spaceship Operator (<=>). This operator is used to compare expressions.

It will Return 0 if values on either side are equal, Return 1 if the value on the left is greater, Return -1 if the value on the right is greater.

<?php

echo 5 <=> 5; // Output 0 as 5 equals to 5
echo 4 <=> 5; // Output -1 as 4 is less than 5
echo 6 <=> 5; // Output 1 as 6 is greater than 5

Example :

Suppose, we have an array of products having product name & price like below :

$products = [
                ['name' => 'Product 1', 'price' => '25'],
                ['name' => 'Product 2', 'price' => '50'],
                ['name' => 'Product 3', 'price' => '46'],
                ['name' => 'Product 4', 'price' => '80'],
                ['name' => 'Product 5', 'price' => '15'],
            ];

And we want to sort it by price so that products with the highest price should come first on the array. For that, we can use usort function of PHP with a spaceship operator like below :

<?php

usort($products, function ($prod1, $prod2) {
    return $prod2['price'] <=> $prod1['price'];
});

print_r($products);

Output :

// The output will be sorted products by price in descending order.

$products = [
                ['name' => 'Product 4', 'price' => '80'],
                ['name' => 'Product 2', 'price' => '50'],
                ['name' => 'Product 3', 'price' => '46'],
                ['name' => 'Product 1', 'price' => '25'],               
                ['name' => 'Product 5', 'price' => '15'],
            ];

Null coalescing operator:

Another cool operator is Null Coalescing Operator (??). which can be replacement of the ternary operator ( isset($a) ? $a : $b ) in conjunction with isset() function.

If you ever used Javascript or VueJs you might be familiar with this operator already.

The null coalescing operator returns its first operand if it exists and is not NULL; otherwise, it returns its second operand.

<?php

$authorName = $author ?? 'Unknown'; 
// Output author name if $author is set or else 'Unknown'

// This is equivalent to:
$authorName = isset($author) ? $author : 'Unknown';

The null coalescing operator can be chained and will return the first defined value from chain.

<?php

$authorName = $author ?? $currentUser ?? 'Unknown';

It will return author name from first defined value out of $author, $currentUser if both are not set then return 'Unknown'.

...

Top comments (0)