PHP ?? (Null Coalescing) and ?: (Ternary Shorthand)
37
?: — Ternary operator (shorthand)
Available since PHP 5.3 (full ternary existed earlier; shorthand since 5.3), return the left value if it is truthy, otherwise return the right value.
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: Triggers a notice if the left variable is undefined.
?? — Null coalescing operator
Available since PHP 7.0, return the left value if it exists and is not null, otherwise return the right value.
Syntax: expr1 ?? expr2
Example:
$name = $_GET['name'] ?? 'Guest';
// Equivalent to
$name = isset($_GET['name']) ? $_GET['name'] : 'Guest';
Key differences vs ?:
- Does not raise notices for undefined variables
- Checks only for null, not truthiness
Practical Comparison & 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 safe defaults without notices