Elvis Operator Not Used
debt(d3/e1/b3/t7)
Closest to 'default linter catches the common case' (d3). The detection_hints list rector, php-cs-fixer, and phpcs — all standard PHP code-style tools that ship with rules flagging `$x ? $x : $default` patterns. These are commonly enabled by default or in standard rulesets, placing this squarely at d3.
Closest to 'one-line patch or single-call swap' (e1). The quick_fix is a direct single-expression substitution: replace `$x ? $x : 'default'` with `$x ?: 'default'` or `$x ?? 'default'`. Rector can automate this. No structural change needed.
Closest to 'localised tax' (b3). The choice affects any PHP web, CLI, or queue-worker context (broad applies_to) but each individual misuse is isolated to its expression. It doesn't shape architectural decisions — it's a stylistic tax paid at the call-site level, not across the whole codebase, so b3 fits better than b5.
Closest to 'serious trap (contradicts how a similar concept works elsewhere)' (t7). The misconception field explicitly calls out that ?: and ?? are commonly believed interchangeable but behave differently for falsy values like 0, '', and false. Using ?: instead of ?? for nullable values silently drops valid 0 or false data in production — a documented gotcha that contradicts reasonable developer intuition about 'null-safe' shorthand, warranting t7.
Also Known As
TL;DR
Explanation
PHP 5.3 introduced the shorthand ternary (Elvis) operator: $x ?: $y is equivalent to $x ? $x : $y. It eliminates repeating the condition variable. Note: ?: triggers E_NOTICE for undefined variables — for null checks on potentially undefined keys use ?? instead. Use ?: when the variable is defined and you want the first truthy value; use ?? when the variable may be undefined and you want the first non-null value.
Common Misconception
Why It Matters
Common Mistakes
- $value ? $value : $default when $value ?: $default is cleaner.
- Using ?: instead of ?? for array keys — $arr['key'] ?: 'default' triggers a notice if 'key' doesn't exist.
- ?: for nullable values where 0 or '' should not trigger the fallback — use ?? instead.
- Chaining ternaries without using ?: making the intent unclear.
Code Examples
// Repetition — same variable twice:
$title = $post->title ? $post->title : 'Untitled';
$displayName = $user->name ? $user->name : 'Anonymous';
$port = $config['port'] ? $config['port'] : 8080;
// Also: $port uses ?: which replaces 0 — bug if port 0 is valid
// Elvis operator — no repetition:
$title = $post->title ?: 'Untitled';
$displayName = $user->name ?: 'Anonymous';
// But: use ?? when value may be null or undefined:
$port = $config['port'] ?? 8080; // 0 is a valid port — use ??
// Correct pairing:
// ?: for 'first truthy value' (0/false/'' trigger fallback)
// ?? for 'first non-null value' (0/false/'' do NOT trigger fallback)