How to use Null coalescing operator in PHP

PHP provides ternary operator for if...else condition if there is simple one line statement. However ternary operator throw undefined error if the variable in condition is not defined.



$x = ($y > 0) ? $y : 0;


This will throw error "PHP Notice:  Undefined variable: y". The null coalescing operator (??) is added to use short if...else condition. The null coalescing operator checks first operand if it exists and is not NULL; otherwise it returns its second operand.


(operand1) ?? (operand2);

Basically The null coalescing operator is same as below:

if (isset() || !is_null()) {
} else {



$x = 'this is text.';

$y = $x ?? 'Nothing to print.';

print($y); // this is text.

So if the value of $x is defined or not null, then it will be assigned to $y, else the operand2 will be assigned to $y.

Take a look at the below example. 


$y = $z ?? 'Nothing to print.';

print($y); // Nothing to print.

Stacking Null Coalese Operator

If you want to check for multiple operand, then you can also check it.



$z = 'this is text.';

print($x ?? $y ?? $z ?? 'Nothing to print.'); // this is text.

This way you can make code more readable and short using the null coalescing operator. I hope you like this article.