Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Null coalescing assignment operator in PHP

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.

<?php
// Pre PHP 7.0

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


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

print_r($user);
//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.

<?php
// From PHP 7.0

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

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

print_r($user);
//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, 8.2, and 8.3), 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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?