What is null coalescing assignment ??= operator in PHP 7.4

Null coalescing assignment operator chaining:

$a = null;
$b = null;
$c = 'c';

$a ??= $b ??= $c;

print $b; // c
print $a; // c

Example at 3v4l.org


From the docs:

Coalesce equal or ??=operator is an assignment operator. If the left parameter is null, assigns the value of the right paramater to the left one. If the value is not null, nothing is done.

Example:

// The folloving lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';

So it's basically just a shorthand to assign a value if it hasn't been assigned before.


The null coalescing assignment operator is a shorthand way of assigning the result of the null coalescing operator.

An example from the official release notes:

$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}

Tags:

Php

Php 7.4