Search code examples
phpphp-7.4

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


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


Solution

  • From the docs:

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

    Example:

    // The following 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.