Null Coalescing Operator in PHP

17/04/2018

Version 7.0 of PHP brought several new features to the language. One of them is the Coalescing Operator or Null Coalescing Operator which allows the return of a default value when the first one is not defined or empty. Its structure is similar to the ternary operator:

value of a variable if it exists and is not empty ?? default value;

For didactic purposes, let's display a phone number only if it is defined and not empty:

if($phone) {
    echo $phone;
} else {
    echo 'Number not informed';
}

In just one line:

echo $phone ?: 'Number not informed';

The above example fails in its failure to check the existence of the variable $phone, which could generate an E_NOTICE. We should use the isset function to work around this situation:

if(isset($phone) and $phone) {
    echo $phone;
} else {
    echo 'Number not informed';
}

In just one line:

echo (isset($phone) and $phone) ? $phone : 'Number not informed';

The purpose of the Coalescing Operator was just to summarize the above types of operations, which are constant when writing algorithms in PHP. Our example would look like this:

echo $phone ?? 'Number not informed';

The operator also allows multiple conditions:

$phone_1 = null;
$phone_2 = '21 4444-5555';

echo $fax ?? $phone_1 ?? $phone_2;


Similar articles

see all articles