Photo of Nathan Shubert-Harbison Nathan Shubert-Harbison

Main content

PHP 7’s badass null coalesce operator

There’s a new PHP on the block, and it’s really, really fast. More than double the requests per second fast. 50% better memory use fast.

This speed increase will be felt everywhere, from small blogs to decoupled API driven interfaces. WordPress has been testing against PHP 7 for a while now, and I’ll be building new WordPress sites against it.

Hello operator

Speed aside, PHP 7 comes with one cool language feature I’m quite fond of, the null coalesce operator. It sounds like a snooze fest at first but it’s actually really cool.

Consider this code:

$page = isset($_GET['page']) ? $_GET['page'] : 1;

How many times have you written that? Probably a lot.

Or the more verbose version:

if ( isset($_GET['page']) ) {
    $page = $_GET['page'];
} else {
    $page = 1;

We’ve all written code like this, and it’s super gross.

The null coalesce operator fixes this. Observe the concise beauty:

$page = $_GET['page'] ?? 1;


And it can be chained too

$content = $_GET['item'] ?? $default ?? 'Nothing to see here';

PHP just keeps looking until it finds a not-null value.

Pretty cool, hey?

The real news around PHP 7 is the crazy performance improvement, but I know I’m going to use the heck out of the null coalesce operator.

More on PHP 7