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

emix picture emix · Nov 29, 2019 · Viewed 9.6k times · Source

I've just seen a video about upcoming PHP 7.4 features and saw this new ??= operator. I already know the ?? operator.

How's this different?

Answer

Pavel Lint picture Pavel Lint · Nov 29, 2019

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.