I see $a ?? 'x', $a ?: 'x' and $user?->name in modern PHP. They look similar. When does each one apply and what are the pitfalls?
DEV3 Developer Forum
What is the difference between ??, ?: and ?-> in PHP?
Every post is reviewed first. Usually reviewed within 24 hours.
1 reply
These three operators handle missing or empty values differently.
Null coalescing ?? (PHP 7)
Returns the left side if it is set and not null, otherwise the right. It never raises an "undefined" warning, so it is ideal for array keys and request data.
$name = $_POST['name'] ?? 'Guest';
$city = $user['address']['city'] ?? 'Unknown'; // safe even if address is missing
$config['debug'] ??= false; // assign if missing (PHP 7.4)
It treats 0, '', '0' and false as valid values.
Short ternary (Elvis) ?:
Returns the left side if it is truthy, otherwise the right.
$title = $input ?: 'Untitled'; // '' , 0, '0', null, false, [] all fall back
It does raise a warning for an undefined variable or key, and it would replace a legitimate 0. So $qty = $_GET['qty'] ?: 1 fails for qty=0 and for a missing key.
Nullsafe ?-> (PHP 8.0)
Short-circuits the whole chain when the left side is null:
$country = $order?->customer?->address?->country; // null if any link is null
It is for method and property access on possibly-null objects. It does not protect against a missing array key and does not catch a non-null value of the wrong type.
Comparison
Value of $x |
$x ?? 'd' |
$x ?: 'd' |
|---|---|---|
null |
'd' |
'd' |
0 |
0 |
'd' |
'' |
'' |
'd' |
| undefined | 'd' |
warning, then 'd' |
Pitfalls
- Do not nest ternaries without parentheses; PHP 8 made unparenthesized nested ternaries a fatal error.
- Overusing
?->can hide logic bugs by turning a missing object into a silent null. Validate at boundaries. isset($a['k'])is equivalent to($a['k'] ?? null) !== null.