PHP 7.4 – Null Coalesce Assignment Operator

PHP 7.4 added a new Null Coalesce Assignment Operator (??=) which is an enhancement of Null Coalesce Operator (??) introduced in PHP 7. The Null Coalesce Assignment Operator (??=) assigns the value of the right-hand parameter if the left-hand parameter is null. If the left-hand parameter is not null then its value is not changed. The Null Coalesce Assignment Operator is sometimes also called as Null Coalesce Equal Operator.

The Null coalesce operator (??) was added so that instead of using isset() along with the ternary operator (?:) we could just use the null coalesce operator (??). Here is an example usage:

// Fetches the value of $_GET['user'] 
// and returns 'nobody' if it does not exist.
$_GET['user'] = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$_GET['user'] = isset($_GET['user']) ? $_GET['user'] : 'nobody';

The Null Coalesce Assignment Operator can now simplify the above statement even further as follows:

$_GET['user'] ??= 'nobody';

This operator is useful if you can checking if the value of variable is null and want to assign it some other value in that case. However, this operator does not works if you are trying to assign the values to a different variable. So, for example in the following case you cannot use the Null Coalesce Assignment Operator, but you can still use Null Coalesce Operator.

$username = $_GET['user'] ?? 'nobody';

More reading:
PHP RFC: Null Coalescing Assignment Operator
Null Coalesce Operator (??)

Leave a Reply