PHP Operators: ??= (Null Coalescing Assignment Operator)

Since PHP 7.4 we have this new operator:

??=

This operator was named with this incredibly easy to remember name: “Null Coalescing Assignment Operator“.

And what does this operator do?

It works like this:

$a ??= 'I am nothing’;

$a will take the value ‘I am nothing’ unless it exists AND it has a non null value.

Examples of null coalescing assigment operator

If $a is not defined:

$a ??= 'I am nothing'; // It takes the value 'I am nothing'

If $a is null it will also take this value:

$a = null;
$a ??= 'I am nothing'; //  It takes the value 'I am nothing'

If $a has an empty value then it will be kept:

$a = '';
$a ??= 'I am nothing'; // It will keep the empty string ''

Or if it is 0 it will keep it:

$a = 0;
$a ??= 'I am nothing'; // It will keep the 0

Any other non null value will be kept:

$a = 10;
$a ??= 'I am nothing'; // I will keep 10

And what can I use it for?

Image this array coming from a form sent by a user:

$user = ['name' => 'Gorka', 'lastname' => 'Urrutia'];

Imagine that user could send this form without the age but you need this value to exist for whatever reason. You could do this to ensure “age” is present in your array:

$user['age'] = $user['age'] ?? 'Unknown';

In this case you could use this operator:

$user['age'] ??= 'Unknown';

Leave a Comment