Skip to content

Instantly share code, notes, and snippets.

@tiagosampaio
Last active February 13, 2024 15:28
Show Gist options
  • Save tiagosampaio/6de54e24a62b9209c0a2234240ac9ac2 to your computer and use it in GitHub Desktop.
Save tiagosampaio/6de54e24a62b9209c0a2234240ac9ac2 to your computer and use it in GitHub Desktop.
PHP: Ternary Operator vs Null Coalescing Operator

Ternary Operator vs Null Coalescing 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)

Array examples

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'

Reference: https://www.designcise.com/web/tutorial/whats-the-difference-between-null-coalescing-operator-and-ternary-operator-in-php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment