What does ??= operator do in PHP with set values

Viewed 367

I have seen this operator ??= in several PHP sentences(PHP7.4) like the following:

$data['comments']['user_id'] ??= 'new value';

I understand that this assign the value of $data['comments']['user_id'] in case that it's set.

What if it is set with one of these?

  • null
  • 0
  • false

I checked over PHP documentation but It isn't clear.

1 Answers

If $data['comments']['user_id'] is not set or is null it will set it to the value of 'new value'

It's shorthand notation for

if(!isset($data['comments']['user_id'])) {
    $data['comments']['user_id'] = 'new value':
}

It's called null-coalescing assignment operator.

It will assign the value on the right to the variable on the left only if the variable on the left is not existing or is null. If it holds any value, even false-ish, nothing will happen.

Related