What's the Difference Between ?? and ?: 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)

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.