Richard Bagshaw

PHP 7 Null Coalescing Operator

Published December 03, 2015 By Richard Bagshaw - Edit page on Github

Written by Richard Bagshaw a php, javascript, vue and react freelancer who lives and works in Nottingham, UK. Follow me on Twitter

In this series of blog posts I will be covering some of the new features available in the upcoming release of PHP 7, I know we are all very busy bees, so this series gets to the point and may be useful for anyone just wanting to understand these features quickly.

The null whut … ?

Firstly, judging a book by its cover you would probably expect this blog post to be quite a lengthy one. However, the opposite is probably true. The null coalescing operator is simple and used when you want to set a default for a variable.

To illustrate this, you may be familiar with this type of code.

$firstname = isset($user->firstname) ? $user->firstname : 'guest';

In PHP5 there is a way todo this using what I would consider a hack, it works exactly the same way, and is less code, but it doesn’t really read that well.

$firstname = @$user->firstname ?: "guest";

Essentially, all we are doing here is using a ternary operator to check that $user->firstname has been assigned a value, if it has, then we assign that to $firstname

If $user->firstname hasn’t been set, then we assign the string 'guest' to the $firstname.

Simple, and something that I have personally used countless times, however, PHP 7 makes this much easier to handle.

$firstname = $user->firstname ?? 'guest';

Look how much cleaner that is, and it achieves the same task, so no more need to use a verbose ternary operator todo something so simple.

Written by Richard Bagshaw a php, javascript, vue and react freelancer who lives and works in Nottingham, UK. Follow me on Twitter