PHP Null Coalescing Assignment (??=)

 ← Dev Articles
👍 0
👎 0

PHP Null-Coalescing Assignment (??=)

The PHP Null-Coalescing Assignment operator ??= is a shorthand that combines the null coalescing operator ?? with an assignment = operator.


Some benefits of the null coalescing assignment operator is it reduces code verbosity significantly. It’s readable with clear intent for setting defaults. It’s safe and avoids undefined variable notices. It’s efficient with a single operation instead of multiple lines.

Below is 3 different ways of accomplishing the same objective. The value of $variable will be 30. The first example uses the ??= (null-coalescing assignment) operator. Notice it's a shorthand for the other 2 similar methods:

 

 // Null-Coalescing Assignment (all-in-one)

 $variable ??= 30;

 

 // Null Coalescing combined with Assignment

 $variable = $variable ?? 30;

 

 // Ternary Operator combined with Assignment

 $variable = $variable ? $variable : 30;


Here are a few different ways of using the Null-Coalescing Assignment operator
??=

 

 // Variable is null

 $name = null;

 $name ??= 'Peter';

 echo $name; // Output: 'Peter'

 

 // Variable already has a value

 $count = 25;

 $count ??= 30;

 echo $count; // Output: 25 (unchanged)

 

 // Variable doesn't exist

 $location ??= 'Chicago';

 echo $location; // Output: 'Chicago'