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;
// PHP 7+
$x ?? $y;
This is equivalent to:
isset($x) ? $x : $y;
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) |
Expression | echo ($x['a'] ?: 'hello') | echo ($x['a'] ?? 'hello') |
---|---|---|
$x = ['a' => 2]; | 2 | 2 |
$x = ['a' => false]; | 'hello' | "" (false) |
$x = ['a' => null]; | 'hello' | 'hello' |
$x = ['b' => 5]; | 'hello' (and Notice: Undefined variable: x) |
'hello' |