PHP

Null Coalescing Operator

Null Coalescing Operator

Hello Everyone, Welcome to my blog. First of all, for those people who don’t know anything about me please check out this link for more information. 

If you want to connect with me or want to share your view or anything, please feel free to write a comment below or write me an email on my email id i.e ranade.ashish11@gmail.com. I will definitely try to address all your queries. Let’s get started.

Today I am going to discuss the new feature in PHP 7 i.e. “Null Coalescing Operator”.

PHP 7 brings a new rather handy feature null coalescing operator. This new feature is similar to the ternary operator that we were using in older versions of PHP (PHP 5 & greater). As per the ternary operator, we are getting the second element if the condition is true, else, the third element if a statement is false. But, PHP 7 allows us to skip the second element and gives us a short form to use this feature. Please follow the below example for the reference.

// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16

Here, on the 3rd line PHP checks if the variable $a is set i.e. isset() (to be precise) or not then it will output the next parameter. In our general coding language, it would be like this.

if(isset($a)){
   echo $a;
}else{
   echo 2;
}

For the 4th line, the same process will be followed. PHP first checks if the variable $a is set or not, then, check if $b is set or not else it will output the last element. In general, the execution will be.

if(isset($a)){
    echo $a;
}elseif(isset($b)){
    echo 16;
}else{
    echo 7;
}

This is one of the small features in PHP which enhances the performance. This feature is very useful because, as we are using a number of loops in our code and if PHP gets a chance to skip through those conditions it will increase the performance of our script.

That’s all for now. Feel free to leave a comment below. Let me know what you think about this blog. Good bye and happy coding 🙂

Tagged

Leave a Reply

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

*

code