# Null Coalesce Operator

> Section in “New and Extended Functionality › Language Features” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/language-features/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:

``` php
$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:

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

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

``` php
$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:

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

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

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

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

---

Previous: [is_object() and Incomplete Classes](https://php7explained.com/new-and-extended-functionality/language-features/is_object-and-incomplete-classes/index.html.md) | Next: [Null Coalescing Assignment Operator](https://php7explained.com/new-and-extended-functionality/language-features/null-coalescing-assignment-operator/index.html.md)
