Null Coalescing operator in PHP. Simple explanation with examples

A new feature in PHP 7 is the Null Coalescing operator.

Coalescing” refers to the process of combining many things into a single unit.

The “??” symbol represents the Null Coalescing Operator.

It returns the first operand provided it exists and is not null.
Otherwise, it will return the second operand.

The null coalescing operator uses the following syntax.

Null Coalescing Syntax

The code executes from right to left.

The right side operand which is not null by default would be the return value if the left operand is null.

In case the left operand is NOT null, it would be this one used as the return value.

Example: Variable is Null (Not Set)

Null Coalescing is used for setting default values.

Here, $a variable is declared but not initialized. So it is not set yet.

Now using Null Coalescing would echo the default value.

NOTE: We could explicitly set the $a value to null and have the same result.

Example: Variable is Set

Null Coalescing would echo the leftmost value provided that the variable is set.
(click on the image to open in a new tab)

Here, $a variable is also initialized. So using the Null Coalescing would echo the leftmost value.

What is the advantage of using null coalescing operator instead of if…else statements?

The equivalent of the above code in a plain if…else statement would be as follows:

The equivalent of a Null Coalescing operator using an if…else statement.
(click on the image to open in a new tab)

The null coalescing operator allows for more compact code and readable code.

Also, using the above code without using the isset method would cause a warning.

$a variable is undefined.
(click on the image to open in a new tab)

The use of the isset method in the Null Coalescing operator is implied, making it easier to use.

Omitting to declare $a won’t cause a warning.
(click on the image to open in a new tab)

Null Coalescing Supports Chaining

We can chain multiple checks in a single line, making it easier to handle multiple fallback options.

For example:

Example of chaining with Null Coalescing.
(click on the image to open in a new tab)


Conclusion

While if…else statements offer more flexibility for complex conditions where deep nesting is necessary, the null coalescing operator is a powerful tool for setting default values and checking multiple variables through chaining. 

Null Coalescing operator works with functions, array elements, and object properties.

Although my blog doesn’t support comments, feel free to reply via email or X.

Privacy Policy Lambros Hatzinikolaou © 2024 — Today. All rights reserved.