Today I Learned Writer

How to PHP Null Coalesce

As a developer primarily working with PHP the language doesn't hold that many secrets anymore. Yet still there are new tricks to learn, I recently found out as I was introduced to the so called Null Coalescing operator. The proposal for this new feature was done in 2014, the RFC here, and it was implemented and merged into the PHP master branch late 2014 (here). The reason this is such a cool operator is because it allows for less verbose code, more efficiency and more clarity, win-win-win.

In practice

As an example let's say you're working with GET parameters and want to check if they exist, and if not set a default value. Now in the really old days you'd have to do something like the following:

if (isset($_GET['key'])) {
  $my_var = $_GET['key'];
}
else {
  $my_var = 'default value';
}

The above of course can also be achieved in the shorter Ternary Operator, like so:

$my_var = isset($_GET['key']) ? $_GET['key'] : 'default value';

But that still is quite verbose. In comes the Null Coalesce Operator:

$my_var = $_GET['key'] ?? 'default value';

So basically it checks if your variable is set and if it is a 'true' value. It won't emit a notice, it has an isset() baked in, how lovely. The most beautiful thing is that it can be chained, so you can have multiple fallbacks:

$my_var = $_GET['key'] ?? $_GET['key_2'] ?? 'default value';

So there you have it. The most important lesson I've learned is that perhaps I just need to keep myself up to date on the progress of the language, because it keeps moving and new features and improvements are added all the time.