PHP null coalescing operator (??)

June 4, 2022  ‐ 1 min read

The null coalescing operator was introduced as one of the new features in PHP 7.0.

It provides you some syntactic sugar for setting fallback values in cases where a value is NULL. Before it was common to handle such cases with a ternary (... ? … : …) in combination with isset().

For example:

<?php

$quantity = isset($_POST['quantity']) ? $_POST['quantity'] : 0;

With the null coalescing operator we can write the above as follows:

<?php

$quantity = $_POST['quantity'] ?? 0;

If the first operand (value before the ??) exists and its value does not equal NULL then $quantity is set to this value. Otherwise $quantity is set to the second operand (value after the ??).