DH
5 min read

How to do the shorthand conditional ternary in PHP

PHP 5.3 added support for shorthand conditional ternary operators.

php

Most programmers are familiar with ternary operators. While most languages have their own shorthand conditional syntax, PHP added support for a shorter form in PHP 5.3 — letting you leave out the middle operand entirely. This shorthand is often called the Elvis operator (?:) because ?: vaguely resembles Elvis Presley's hair and raised eyebrow.

Let's walk through every form of a PHP conditional, from longest to shortest, and then look at the edge cases you need to understand to use ?: safely.


1. The Traditional if / else

<?php

$a = false;
$b = 'b';

if ($a) {
echo $a;
} else {
echo $b;
}

This is the most explicit form — clear, but verbose.


2. The Standard Ternary Operator

<?php

$a = false;
$b = 'b';

echo $a ? $a : $b;

The ternary operator takes three operands: the condition, the value if true, and the value if false. When the condition is truthy, the middle operand is returned; otherwise the right-hand operand is used.


3. The Shorthand Elvis Operator (?:)

<?php

$a = false;
$b = 'b';

echo $a ?: $b;

Since PHP 5.3, you can omit the middle operand. The expression $a ?: $b is equivalent to $a ? $a : $b — if $a is truthy, it is returned as-is; otherwise $b is returned. This avoids repeating $a twice, making the intent cleaner.


Practical Use Case: Default Values in Templates

One of the most common places you'll find ?: is in template or view files, where you want to fall back to a sensible default when a variable is empty or unset.

<span>Hello there, <?php echo $fullName ?: 'Guest' ?></span>

This prints the user's full name if it's a non-empty, truthy string — and falls back to "Guest" otherwise. Without ?:, you'd need a full if / else block or repeat the variable in a ternary, cluttering the template.

A few more real-world patterns:

<?php

// Use a config value, or fall back to a hard-coded default
$timeout = $config['timeout'] ?: 30;

// Use the first non-empty item in a list
$displayName = $user->nickname ?: $user->firstName ?: $user->email;

Edge Cases: Falsy Values to Watch Out For

Because ?: tests for truthiness — not merely for null — it will fall through to the right-hand side for any falsy value, including:

ValueTypeFalsy?
falsebool✅ Yes
nullnull✅ Yes
0int✅ Yes
0.0float✅ Yes
""string✅ Yes
"0"string✅ Yes
[]array✅ Yes

This matters in practice. If $count holds a legitimate value of 0, then $count ?: 'none' will incorrectly return 'none':

<?php

$count = 0;
echo $count ?: 'none'; // Outputs: none ← probably not what you wanted!

In cases like this, you need the full ternary or an explicit isset / is_null check.


Elvis (?:) vs. Null Coalescing (??) — Know the Difference

PHP 7.0 introduced the null coalescing operator ??, which is often confused with ?:. They are not the same:

OperatorFalls back when…Generates E_NOTICE for undefined var?
?: (Elvis)Left side is falsy (false, 0, "", [], null…)✅ Yes
?? (Null coalescing)Left side is null or undefined❌ No
<?php

$value = 0;

var_dump($value ?: 'default'); // string(7) "default" — 0 is falsy
var_dump($value ?? 'default'); // int(0) — 0 is not null

Another key difference: ?? will not emit an E_NOTICE (or E_WARNING in PHP 8) when the left-hand variable is undefined, making it safer for reading from $_GET, $_POST, or optional array keys:

<?php

// Safe — no notice even if 'name' key is absent
$name = $_GET['name'] ?? 'Anonymous';

// Risky — triggers a notice if 'name' key is absent
$name = $_GET['name'] ?: 'Anonymous';

Rule of thumb: use ?? when your concern is null or missing; use ?: when you want to catch all falsy values and you know the variable is defined.


When to Avoid ?:

  • Numeric inputs that can legitimately be 0 — use ?? or a strict check instead.
  • Chained ternaries — PHP's ternary operator is left-associative, which leads to confusing results when you nest them. Prefer explicit if/else or separate statements.
  • Arrays that might be empty but valid — an empty array [] is falsy, so $items ?: [] will always return [] even when $items is already [].

Quick Reference

<?php

// Long form
if ($a) { $result = $a; } else { $result = $b; }

// Standard ternary
$result = $a ? $a : $b;

// Elvis (shorthand ternary) — PHP 5.3+
$result = $a ?: $b;

// Null coalescing — PHP 7.0+
$result = $a ?? $b;

Understanding the distinction between these three forms means you can pick the right tool for each situation and avoid subtle bugs caused by PHP's type coercion rules.

Damian Hodgkiss

Damian Hodgkiss

Senior Staff Engineer at Sumo Group, leading development of AppSumo marketplace. Technical solopreneur with 25+ years of experience building SaaS products.

Creating Freedom

Join me on the journey from engineer to solopreneur. Learn how to build profitable SaaS products while keeping your technical edge.

    Proven strategies

    Learn the counterintuitive ways to find and validate SaaS ideas

    Technical insights

    From choosing tech stacks to building your MVP efficiently

    Founder mindset

    Transform from engineer to entrepreneur with practical steps