Null coalescing operator in PHP 7


Let us consider a code of checking the age first. It checks whether the ‘age’ is given in the form or not. If it’s not given, then it says ‘not mentioned’. When it’s given it just spits out the age. Very basic thing we normally did when php 7 had not come.

$age = isset($_GET['age']) ? $_GET['age'] : 'not mentioned';


As usual it’ll give an output of – ‘not mentioned.’ Now we write this code with the age given.

$_GET['age'] = 10;

$age = isset($_GET['age']) ? $_GET['age'] : 'not mentioned';


As expected it gives us the age now, which is 10. But php 7 has made it more simple and fun to train the gun in a really simple way. No more you have to chack whether the variable value is set ot not. We can write the same code in a more simple way.

$age = $_GET['age'] ?? 'not mentioned';

Run the code and the output is:

string(13) "not mentioned"

And provide the value you’ll get the value right away. It’s so simple.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s