Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?
When do they behave d
Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:
The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.
Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:
So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.
Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.
Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples