Member-only story
Understanding PHP’s Null Coalescing Operator (??)
The Null Coalescing Operator (??)
Introduced in PHP 7.0, the null coalescing operator, represented by ??
, is a simple but effective feature for streamlining code. It allows for cleaner, more readable handling of null or unset variables.
The primary use of ??
is to check if a variable is set and not null. If it's either unset or null, the operator allows you to provide a default value.
For example:
$name = $_GET['name'] ?? 'Unknown';
In this code, $name
is assigned the value of $_GET['name']
if it is set and not null. If not, it defaults to "Unknown".
The operator can also be chained to check multiple variables:
$foo = $foo ?? $bar ?? 'baz';
Here, PHP first checks $foo
. If it's null or unset, it checks $bar
. If neither is set, it assigns the value 'baz'
.
The Null Coalescing Assignment Operator (??=)
PHP 7.4 introduced the null coalescing assignment operator (??=
), which simplifies the process of assigning a value to a variable only if that variable is not already set or is null.
For example, in a function where a parameter may or may not be passed: