PHP Null Coalescing Operator ??

 ← Dev Articles
👍 0
👎 0
The null coalescing operator ?? is used similar to the elvis operator ?:  In the example below the value of $var3 will only be the value of $var2 if $var1 is null.  With no value will $var3 be the value of $var1. 
 
Example 1:

$var1 = null;  // it's null
$var2 = 15;
$var3 = $var1 ?? $var2; // the value is 15

OR
$var1;  // it's undfefined
$var2 = 15;
$var3 = $var1 ?? $var2; // the value is 15

In Example 1 above the value of $var3 will be the value of $var2.  This is because value of $var1 is null or undefined.  If $var1 is any value besides null, the value of $var3 would be the value of $var1.  That case is displayed in Example 2 below.

In Example 2:

$var1 = 3;
$var2 = 15;
$var3 = $var1 ?? $var2;   // the value is 3