PHP – Null Coalescing Operator

Today very short, but I think helpful post about null coalescing operator. As I guess, you use a lot of if/else expressions in code. Sometimes we must check simple condition to set variable. There are two standard approaches. First, using if/else:

if (my_condition) {
    $var = 'Yep!';
} else {
    $var = 'Nope';
}

It’s ok, but for something like this, too long. Fortunately we can use ternary operator to make this only in one line:

$var = (my_condition) ? 'Yep!' : 'Nope';

And it works perfectly. So what about null coalescing operator? It’s “new” because has been introducted in PHP 7.0. With that operator, you can make some conditions even simpler. Very often thing: get data from POST or GET (or other source), but we must first check, if that data really exists. With this operator, it’s very simple:

// Standard approach
$var = isset($_POST['var']) ? $_POST['var'] : 'Nope';

// With new operator
$var = $_POST['var'] ?? 'Nope'

In that case, PHP will check if $_POST[‘var’] exists and if it’s not null. If both conditions are met, $var will be $_POST[‘var’]. If not, it will be “Nope”. As you can see, it’s perfect option to set any optional data and using some default values if they don’t exist. It’s very short option, because we don’t have to write isset and duplicate $_POST[‘var’] every time. 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.