Null Coalesce Operator

April 6, 2017

So today I learned something cool, Chris Fidao posted on Twitter the following message:

Never saw this, wonder if I can avoid using ugly `isset()`
https://wiki.php.net/rfc/isset_ternary

Which caught my eye and so I decided to look more into it. What I found is an awesome Null Coalescing Operator that came with PHP7, something new and so helpful to reduce code and make it easier to see and read.

echo $bar ?? 'foo';

Basically what this does is if $bar is not defined it will output foo instead of throwing an Undefined variable error.

Before this you would have to write:

echo isset($bar) ? $bar : 'foo';

So you can see how much better it is.

Here are some examples I ran on PsyShell that illustrate this:

>>> $bar
PHP error:  Undefined variable: bar on line 1

>>> $bar ?: 'foo'
PHP error:  Undefined variable: bar on line 1

>>> isset($bar) ? $bar : 'foo'
=> "foo"

>>> $bar ?? 'foo'
=> "foo"

I'll for sure be using this in the future, and I hope I was able to show you the value of it.

The full documentation of this feature is at the PHP Manual - Operators Comparison.

Posted: Apr 06, 2017