Null Coalesce Operator

As we have previously learned, PHP – as opposed to some other programming languages – does not require you to declare a variable before using it. You are also not required to initialize a variable in PHP, which often leads to some sluggishness:

$username = $_POST['username'];

var_dump($username);

We are trying to access an array key, without actually worrying about whether it exists. If the key username does not exist in $_POST, PHP will just assume a null value, but also emit a notice because you have tried to access a non-existing array index:

Notice: Undefined index: username in ...
NULL

Good code should not emit any errors, warnings, or notices. The simple reason for that is that you want actual errors to stand out, and hiding them between hundreds or even thousands of notices in your error log does not make your life a lot easier when it comes to debugging.

We can avoid the notice with an if statement:

if (isset($_POST['username'])) {
    $username = $_POST['username'];
} else {
    $username = null;
}

Now this is much cleaner, but rather verbose. How about a ternary operator:

$username = isset($_POST['username']) ? $_POST['username'] : null;

This is still rather verbose because we have to repeat $_POST['username']. PHP 7 offers the new null coalesce operator ?? that allows us to write this line in a more concise way:

$username = $_POST['username'] ?? null;

Of course, this also works with a non-null value:

$username = $_POST['username'] ?? 'anonymous';

The null coalesce operator checks whether the expression before ?? is null. If so, its value is used. Otherwise the provided fallback value will be used.