The Null Coalescing Operator ?? and The Ternary Operator ?: in PHP



While I was working on a PHP project I came across those two notations ?? and ?: and realized that it’s not always obvious to determine when using one versus the other. That was a good candidate for a blog post.

While those operators aren’t new, they aren’t used that often, so let’s try to demystify them.

What do they shorten?

Those two operators give a way to write more concise code and shorten expressions used in PHP.

?? is same as ( !isset() || is_null() )


if ( ! $x ) { echo $x; } else { echo $y; } to echo $x ?: $y

The Null Coalescing Operator ??

Basically, this operator will return the first non NULL value. This structure will return $value1 if it’s not NULL or $value2:

echo $value1 ?? $value2;

The great thing about this operator is that you can combine multiples variables, for instance:

echo $value1 ?? $value2 ?? $value3 ?? $value4;

and the first non NULL value will be echoed in this sample.

The Ternary Operator ?:

This operator isn’t going to check only via is_null() but also: empty() and !isset()

This would lead to a much cleaner code from this:

if( isset( $_GET['my_variable'] ) && !is_null( $_GET['my_variable'] ) ) {
            $my_variable = $_GET['my_variable'];
        } else if( !empty( $my_defined_variable ) ) {
             $my_variable = $my_defined_variable; 
        } else {
            $my_variable = 'whatever';

to this:

$my_variable = $_GET['my_variable'] ?? $my_defined_variable ?: 'whatever';

Leave a Reply