Null Coalescing Operator Not Used
Also Known As
?? operator
null coalescing
??= operator
TL;DR
Using isset() + ternary or if/else chains when the null coalescing operator (??) or null coalescing assignment (??=) would be cleaner and more idiomatic.
Explanation
PHP 7.0 introduced ?? which returns the left operand if it exists and is not null, otherwise the right. PHP 7.4 added ??= which assigns only if the variable is null. These replace the common isset($x) ? $x : $default pattern. The operator also works on array keys and chained access: $config['db']['host'] ?? 'localhost'. Unlike the ternary shorthand (?:), null coalescing does not trigger a notice for undefined variables.
Common Misconception
✗ ?? and ?: are the same — ?: triggers E_NOTICE for undefined variables; ?? suppresses the undefined notice and only checks for null.
Why It Matters
isset($x) ? $x : $default is verbose and error-prone when chaining multiple fallbacks — $a ?? $b ?? $c ?? 'default' is cleaner and correctly handles undefined variables.
Common Mistakes
- Using isset($x) ? $x : $default when $x ?? $default is available (PHP 7+).
- if (!isset($arr[$key])) $arr[$key] = []; — use $arr[$key] ??= [].
- Using ?: which triggers notices for undefined variables instead of ??.
- Forgetting ?? works on chained array access: $data['user']['name'] ?? 'Unknown'.
Code Examples
✗ Vulnerable
// Verbose — pre-PHP 7 style:
$name = isset($_GET['name']) ? $_GET['name'] : 'Guest';
$timeout = isset($config['timeout']) ? $config['timeout'] : 30;
$locale = isset($user) && isset($user->locale) ? $user->locale : 'en';
// Assignment:
if (!isset($cache[$key])) {
$cache[$key] = [];
}
✓ Fixed
// Clean — null coalescing:
$name = $_GET['name'] ?? 'Guest';
$timeout = $config['timeout'] ?? 30;
$locale = $user?->locale ?? 'en';
// Null coalescing assignment:
$cache[$key] ??= [];
// Chained:
$value = $request->get('x') ?? $config['x'] ?? $defaults['x'] ?? null;
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
16 Mar 2026
Edited
22 Mar 2026
Views
25
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 8
Perplexity 6
Ahrefs 2
Google 2
Unknown AI 2
ChatGPT 1
Also referenced
How they use it
crawler 20
crawler_json 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: Low
⚡ Quick Fix
Replace isset($x) ? $x : $default and array_key_exists + ternary with the ?? operator — it's null-safe, handles undefined array keys without notices, and is chainable
📦 Applies To
PHP 7.0+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
isset($x) ? $x : $default pattern; $arr['key'] ? $arr['key'] : 'default' double access; ternary returning same variable as condition
Auto-detectable:
✓ Yes
rector
php-cs-fixer
phpcs
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✓ Auto-fixable
Fix: Low
Context: Line