PHP 7 – Null Coalescing Operator

In PHP 7, another component Null Coalescing Operator has been added.

Null Coalescing Operator represented by ??. It is combination of ternary operation with isset() function.

The Null Coalescing Operator will return its operand if it exists and is not NULL. Otherwise it will return its second operand.

Example of Null Coalescing Operator

<?php
   // get the value of $_GET['username'] and returns 'not available'

   // if username is not available
   $username= $_GET['username'] ?? 'not available';
   echo $username;
   echo "<br>";

   // Equivalent code using ternary operator
   $username= isset($_GET['username']) ? $_GET['username'] : 'not available';
   echo $username;
   echo "<br>";

   // Chaining ?? operation
   $username= $_GET['username'] ?? $_POST['username'] ?? 'not available';
   echo $username;
?>


//Output: 
not available
not available
not available
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial