Elvis Operator Not Used
Also Known As
?:
Elvis operator
shorthand ternary
TL;DR
Writing $x ? $x : $y instead of $x ?: $y — the Elvis operator (?:) returns the left operand if truthy, otherwise the right, eliminating the repeated expression.
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
✗ ?: and ?? are interchangeable — ?: returns the left side if it is truthy (so 0, '', false trigger the fallback); ?? returns the left side if it is not null (so 0, '', false do NOT trigger the fallback).
Why It Matters
Using the wrong operator between ?: and ?? for numeric or boolean values silently replaces valid 0 or false with a default — a common source of subtle bugs in form handling.
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
✗ Vulnerable
// 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
✓ Fixed
// 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)
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
16 Mar 2026
Edited
22 Mar 2026
Views
21
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Perplexity 6
Amazonbot 6
Ahrefs 2
Unknown AI 2
Majestic 1
Google 1
Also referenced
How they use it
crawler 17
crawler_json 1
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: Low
⚡ Quick Fix
Use $x ?: 'default' (Elvis operator) for falsy fallbacks or $x ?? 'default' for null-only fallbacks — the Elvis operator is the ternary without the middle operand
📦 Applies To
PHP 5.3+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
$x ? $x : 'default' that could be $x ?: 'default'; not using shorthand ternary where available
Auto-detectable:
✓ Yes
rector
php-cs-fixer
phpcs
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✓ Auto-fixable
Fix: Low
Context: Line