Introduced in PHP 7, the null coalescing operator (??
) has the following syntax:
// PHP 7+
leftExpr ?? rightExpr;
Which means that leftExpr
is returned when leftExpr
exists and is NOT null
; otherwise it returns rightExpr
. For example, all the following statements are equivalent:
// PHP 7+
// 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;
}
Please note that the null coalescing operator only evaluates to the right-hand side operand if the left-hand side operand is null
or not set. This means that all other falsy values return the left-hand side operand.
The coalescing can also 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.
Starting with PHP 7.4, you can also use the null coalescing assignment operator ((??=)
).
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.