Null Coalescing Assignment Operator in PHP 7.4

Web Development

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.

Null Coalescing Assignment Operator in PHP 7.4

Basically, this operator helps to remove 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:

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

After release of PHP 7 we were able to achieve the same using below code:

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

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

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

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

0 0 vote
Article Rating

Tags: #PHP, #PHP7, #PHP7.4

Related Post

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments