Null Coalescing Assignment Operator in PHP 7.4

arifpavel wrote on October 27, 2020
php7.4

Added with PHP 7, the coalesce operator (??) comes in handy when we need to use a ternary operator in conjunction with isset(). It returns the first operand if it exists and is not NULL. Otherwise, it returns the second operand. Here is an example:

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

What this code does is pretty straightforward: it fetches the request parameter and sets a default value if it doesn’t exist. The meaning of that line is clear, but what if we had much longer variable names as in this example from the RFC?

$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';

In the long run, this code could be a bit difficult to maintain. So, aiming to help developers to write more intuitive code, this RFC proposes the introduction of the null coalescing assignment operator (??=). So, instead of writing the previous code, we could write the following:

$this->request->data['comments']['user_id'] ??= ‘value’;

If the value of the left-hand parameter is null, then the value of the right-hand parameter is used.
Note that, while the coalesce operator is a comparison operator, ??= is an assignment operator.

This proposal has been approved with 37 to 4 votes.