Sunday, December 14, 2025
HomeLanguagesWhat is the use of Null Coalesce Operator ?

What is the use of Null Coalesce Operator ?

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

Output when values are not Set
Name : Default
Age : Default
 
Output when values are Set
Name : GFG
Age : 18
RELATED ARTICLES

Most Popular

Dominic
32447 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6816 POSTS0 COMMENTS
Nicole Veronica
11953 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12031 POSTS0 COMMENTS
Shaida Kate Naidoo
6951 POSTS0 COMMENTS
Ted Musemwa
7202 POSTS0 COMMENTS
Thapelo Manthata
6898 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS