Web Development

Null Coalescing Assignment Operator in PHP 7.4

PHP 7.4 comes with many good features but this one of my personal favorite. I am sure as a developer, you will also love this short and clean version of code.
PHP Code

PHP 7.4 has many good features, but this is one of my favorites. I am sure as a developer, you will also love this short and clean version of the code.

This operator helps to remove the use of isset() function. Let’s see how:

In some cases, we need to check if a variable exists then assign that value else assign some default value. before PHP 7 we used to do this as below:

$data['username'] = (isset($data['username']) ? $data['username'] : 'guest');

After the release of PHP 7, we were able to achieve the same using the following:

$data['username'] = $data['username'] ?? 'guest';

After the release of PHP 7.4, we can further simplify this as below:

$data['username'] ??= 'guest';

All the above code block does the same thing. So pretty clear, right?

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *