Php Null Coalescence

Published:2021-09-04
Share:

Since PHP 7, you can use, null coalescing operator ??, it eleminates the need to check if the variable is not NULL before accessing its value,

Before PHP 7 you needed isset() function for checking. The Null coalescing operator comes to save your time, its returns the first operand if it's exists and is not NULL, otherwise the second operand returned.


Here is an example:

<?php
   // if room is not passed
   $room = $_GET['room'] ?? 13;
   print($room);
   print("<br>");
   // same code before PHP 7
   $room = isset($_GET['room']) ? $_GET['room'] : 13;
   print($room);
   print("<br>");
   
   // ?? maybe chained as desired
   $room = $_GET['room'] ?? $_POST['room'] ?? 13;
   print($room);
?>

It prints the folowing:

13
13
13