What Is the Null Coalescing Operator in PHP?

Find out what the null coalescing operator (??) is in PHP and how it works

Introduced in PHP 7, the null coalescing operator (??) has the following syntax:

// PHP 7+
expr1 ?? expr2;

Which means that expr1 is returned when expr1 exists and is NOT null; otherwise it returns expr2. For example, all of the following statements are equivalent:

// using the null coalescing operator
$x ?? $y;
// using the ternary operator
isset($x) ? $x : $y;
// using if/else
if (isset($x)) {
    return $x;
} else {
    return $y;

For a null coalescing operator, the only thing that matters is that the variable exists and is not null so even falsy values are given a pass.

??= (Null Coalescing Assignment Operator)

Starting PHP 7.4+, you can use the null coalescing assignment operator (??=) — a shorthand to assign a value to a variable if it hasn't been set already. Consider the following examples, which are all equivalent:

$x = (isset($x) ? $x : $y);

$x = $x ?? $y;

$x ??= $y;

Coalescing Chaining

The coalescing can be chained (i.e. it returns the first defined/non-null value it encounters), for example:

$x ?? $y ?? $z ?? 'empty'; // output: 'empty'

In case there's no defined value in the coalescing chain, a "Notice: Undefined variable: ..." message is shown.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.