Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Null coalescing assignment operator in PHP

May 4, 2020 ·

When PHP 7.0 released, it has added many nice things in PHP’s toolbelt of utilities. One of the things among this was Null coalescing assignment operator (??).

So basically, the operator can be used for the scenarios where you need to check if the variable is set or not before assigning it to an another variable. For instance, check the following code which you might be writing pre PHP 7.0 era.

// Pre PHP 7.0

$user = [
    'name' => 'Amit', 
    'job' => 'Developer'

if (!isset($user['job'])) {
    $user['job'] = 'Blogger'; 

//Array([name] => Amit [job] => Developer)

The above code code can be reduced to following in PHP 7.0 by using null coalescing assignment operator like so.

// From PHP 7.0

$user = [
    'name' => 'Amit'

$user['job'] = $user['job'] ?? 'Blogger'; 

//Array([name] => Amit [job] => Blogger)

Essentially, the null coalescing assignment operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

You can further make it more tidier by writing it as short-hand version like so.

$user['job'] ??= 'Blogger'; 

As you can see in the example above, it’s now matter of just one line when you need to accomplish something like above. Looks pretty neat and clean, no?

Learn the fundamentals of PHP 8 (including 8.1 and 8.2), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!