What's the Difference Between ?? and ?: in PHP?

A comparison of the Null Coalescing and Evlis/Shorthand Ternary Operator in PHP

?: (Elvis Operator)

The elvis operator (?:) is actually a name used for shorthand ternary (which was introduced in PHP 5.3). It has the following syntax:

// PHP 5.3+
expr1 ?: expr2;

This is equivalent to:

expr1 ? expr1 : expr2;

?? (Null Coalescing Operator)

The null coalescing operator (??) was introduced in PHP 7, and it has the following syntax:

// PHP 7+
$x ?? $y;

This is equivalent to:

isset($x) ? $x : $y;

?: vs. ??

The table below shows a side-by-side comparison of the two operators against a given expression:

Expression echo ($x ?: 'hello') echo ($x ?? 'hello')
$x = ""; 'hello' ""
$x = null; 'hello' 'hello'
$x; 'hello'
(and Notice: Undefined variable: x)
'hello'
$x = []; 'hello' []
$x = ['a', 'b']; ['a', 'b'] ['a', 'b']
$x = false; 'hello' false
$x = true; true true
$x = 1; 1 1
$x = 0; 'hello' 0
$x = -1; -1 -1
$x = '1'; '1' '1'
$x = '0'; 'hello' '0'
$x = '-1'; '-1' '-1'
$x = 'random'; 'random' 'random'
$x = new stdClass; object(stdClass) object(stdClass)

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.