Eduardo Arsand

PHP ?? (Null Coalescing) and ?: (Ternary Shorthand)

222

?: — Ternary operator (shorthand)

Available since PHP 5.3 (the full ternary operator existed earlier), ?: returns the left value if it is truthy; otherwise, it returns the right value. See the PHP 5.3 release notes.

Syntax: expr1 ?: expr2

Example:

$name = $_GET['name'] ?: 'Guest';

// Equivalent to
$name = $_GET['name'] ? $_GET['name'] : 'Guest';

// Truthy Examples
if (true);         // true → truthy
if (1);            // integer non-zero → truthy
if (3.14);         // float non-zero → truthy
if ('hello');      // non-empty string → truthy
if ([1,2,3]);      // non-empty array → truthy
if (new stdClass); // object → truthy

// Falsy Examples
if (false);    // false → falsy
if (0);        // integer zero → falsy
if (0.0);      // float zero → falsy
if ('0');      // string "0" → falsy
if ('');       // empty string → falsy
if ([]);       // empty array → falsy
if (null);     // null → falsy

Important: Using ?: with an undefined variable or array key raises E_WARNING in PHP 8.0+ and E_NOTICE in earlier versions. See the PHP documentation for undefined variables and undefined array keys.

?? — Null coalescing operator

Available since PHP 7.0, ?? returns the left value if it exists and is not null; otherwise, it returns the right value. See the PHP 7.0 release notes.

Syntax: expr1 ?? expr2

Example:

$name = $_GET['name'] ?? 'Guest';

// Equivalent to
$name = isset($_GET['name']) ? $_GET['name'] : 'Guest';

Key differences from ?:

  • Handles undefined variables and array keys without raising a notice or warning.

  • Checks only for null, not truthiness.

Practical comparison and chaining

$val1 = 0;
echo $val1 ?: 'fallback'; // outputs 'fallback'
echo $val1 ?? 'fallback'; // outputs 0

// Chaining ??
$lang = $_GET['lang'] ?? $_SESSION['lang'] ?? 'en';

Summary

  • Use ?: when you want truthy/falsy behavior.

  • Use ?? when you want a default for null or undefined values without a notice or warning.


Comments ({{ modelContent.total_comments }})