PHP example of Null coalescing operator for shorthand If-Else operator

In this example we will see the use of the shortest shorthand of if-else statement to check isset variable in PHP programming language. Using Null coalescing operator we can write shortest if-else statement to check isset value and return it in PHP with less lines of code.

Null coalescing operator

Null coalescing operator is an extension to the refined version of the ternary operator (?:) in PHP and it is available since PHP 7.0. It was one of the coolest features of PHP 7.0 update.

Here is a simple example of PHP’s normal if-else statement:

if( isset($_GET['user']) )  {
    echo $_GET['user'];
}   else {
    echo 'noboday';
}

If we want to write using ternary operator, then we write:

echo isset($_GET['user']) ? $_GET['user'] : 'nobody';

And with extension i.e. Null coalescing operator we can write it like:

echo $_GET['user'] ?? 'nobody'

One can see that ?? operator inside ternary operation syntax checks for the isset of a variable and if it is found set, it returns the value of the variable.

(The Null coalescing operator has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset() )

Conclusion

In this short tutorial you learned about the use of shortest shorthand to check isset of variable of in if-else statement in PHP. Using this operator you can handle the checking of isset of variable and at the same time you can return the value back from the given variable.

Leave a Reply