Ternary Operator in PHP

Ruden
Valeriy Rudenko

What's the difference between ??, ??= and ?: in PHP?
A comparison of the null coalescing and evlis/shorthand ternary operator.

?: 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:

expr1 ?: expr2;

This is equivalent to:

!empty(expr1) ? expr1 : expr2;

?? Null Coalescing Operator

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

expr1 ?? expr2;

This is equivalent to:

isset(expr1) ? expr1 : expr2;

??= Null Coalescing Assignment Operator

The null coalescing operator ??= was introduced in PHP 7.4, and it has the following syntax:

expr1 ??= expr2;

This is equivalent to:

expr1 = expr1 ?? expr2;

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 = 'test'; 'test' 'test'