PHP 7 operators: null coalescing (??) and space ship (<=>)


Difficulty

There are two changes regarding PHP 7, concerning two new operators that have been very useful to me during my years in PHP.

The “null coalescing” Operator: ??

In an expression it will return the left operand if this is not NULL, if this condition does not occur the right operand will be returned.

 $w = $x ?? $y;

The equivalent in the old PHP 5.6 would be (using the ternary operator):

 $w = isset($x) ? $x : $y;

The advantage in using this operator is evident in the simplicity and greater cleanliness of the written code.

The “space ship” Operator: <=>

In an expression it will return 1 if the left operand is greater than the right operand, -1 if the left operand is less than the right operand and 0 if the operands are equal.
It is very similar to the native function strcmp() with the difference that it can operate on any type of data.

 $w = $x <=> $y;

The equivalent in the old PHP 5.6 would be (using the ternary operator):

 $w = ($x < $y) ? -1 : (($x > $y) ? 1 : 0);

Try it at home!

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.