What is the null coalescing operator in PHP7?

October 26, 2018

The null coalescing operator are the two question marks: ?? you often see in code. It returns the first operand if it exists and is not null. Otherwise it returns the second operand. It is used to replace some ternary operations. Here is an example:

<?php
// old way
$var = isset($_GET['variable']) ? $_GET['variable'] : "default_val";
// new way - null coalescing:
$var = $_GET['variable'] ?? "default_val";
// $var will be $_GET['variable']'s value if it existed and was not null. 
// otherwise it will be 'default_val'
// You can safely use the null coalescing operator to reference keys in associative arrays that may not exist

Both of the above lines do the same thing: they set $var to $_GET['variable'] if it is set (if it passes isset()), but if not then it sets $var to 'default_val'.