PHP null coalescing assignment operator with example and syntax

The PHP null coalescing assignment operator (??=) is a shorthand operator that allows you to assign a default value to a variable only if the variable is currently null. It was introduced in PHP 7.4.

Here is an example of how to use the null coalescing assignment operator:

// Example 1$name = null;$name ??= "John";echo $name; // Output: John// Example 2$name = "Mary";$name ??= "John";echo $name; // Output: Mary

In Example 1, the $name variable is null, so the null coalescing operator assigns the value “John” to it. When we print the $name variable, it prints “John”.

In Example 2, the $name variable already has a value (“Mary”), so the null coalescing operator does not assign the default value “John” to it. When we print the $name variable, it prints “Mary”.

The syntax of the null coalescing assignment operator is as follows:

$variable ??= value;

Here, $variable is the variable that you want to assign a default value to if it is currently null, and value is the default value that you want to assign to the variable if it is null.

Note that the null coalescing assignment operator only assigns a default value to the variable if it is currently null. If the variable already has a value (even if it is an empty string or a value that evaluates to false), the operator does not assign the default value to the variable.

Comments