PHP 7 introduced a null-coalescing operator with ?? syntax. This operator returns its first operand if its value has been set and it is not NULL, otherwise it will return its second operand. This operator can be used in a scenario where the programmer wants to get some input from the user and if the user has skipped the input, some default value has to be assigned to the variable.
Uses of Null Coalescing Operator:
- It is used to replace the ternary operator in conjunction with the PHP isset() function.
- It can be used to write shorter expressions.
- It reduces the complexity of the program.
- It does not throw any error even if the first operand does not exist.
Example: If the values of $name and $age are assigned then assigned values will be printed otherwise the default value which is provided in the expression will be assigned to these variables as values.
PHP
<?php echo 'Output when values are not Set' . "\xA<br>" ; // Using ternary operator $name = isset( $_GET [ 'name' ]) ? $_GET [ 'name' ] : 'Default' ; echo 'Name : ' . $name . "\xA<br>" ; // Using Null Coalescing $age = $_GET [ 'age' ] ?? 'Default' ; echo 'Age : ' . $age . "\xA \xA<br><br>" ; echo 'Output when values are Set' . "\xA<br>" ; $_GET [ 'name' ]= 'GFG' ; $_GET [ 'age' ]= '18' ; // Using ternary operator $name = isset( $_GET [ 'name' ]) ? $_GET [ 'name' ] : 'Default' ; echo 'Name : ' . $name . "\xA<br>" ; // Using Null Coalescing $age = $_GET [ 'age' ] ?? 'Default' ; echo 'Age : ' . $age ; ?> |
Output when values are not Set Name : Default Age : Default Output when values are Set Name : GFG Age : 18
My brother suggested I might like this web site.
He was entirely right. This post actually made my day.
You can not imagine simply how much time I had spent for this info!
Thanks!
I’m gone to tell my little brother, that he should also pay a quick visit this web site on regular
basis to take updated from newest gossip.
For latest news you have to visit internet and on world-wide-web
I found this web site as a finest web page for latest updates.
Pretty great post. I simply stumbled upon your weblog and wanted to say that I’ve truly enjoyed browsing your weblog posts.
In any case I will be subscribing for your feed and I am
hoping you write again very soon!
Hi there everybody, here every one is sharing such familiarity, thus it’s fastidious
to read this website, and I used to pay a visit this blog every day.
Your way of describing all in this post is genuinely pleasant, all be
able to without difficulty understand it, Thanks a lot.