← Back to PHP Course | Chapter 3: Operators | Lesson 7 of 8

PHP Ternary Operator

Basic Ternary Operator

condition ? valueIfTrue : valueIfFalse packs a simple two-way choice into a single expression, replacing a 4-line if/else block that only assigns one variable. It reads best when the condition and both outcomes are short and clear — for anything more involved, a real if/else stays more readable.

Example: Basic Ternary Operator

php
<?php
$age = 20;
$status = $age >= 18 ? "adult" : "minor";
echo $status;
?>

Short Ternary Operator

$value ?: $fallback — the short ternary, sometimes called the Elvis operator for how it looks — returns $value itself if it's truthy, or $fallback otherwise. It's shorthand for $value ? $value : $fallback without repeating $value twice.

Example: Short Ternary Operator

php
<?php
$value = "";
$result = $value ?: "fallback";
echo $result;
?>

Null Coalescing Operator

$value ?? $fallback, the null coalescing operator, returns $value unless it's null or entirely undefined, in which case it returns $fallback. Unlike the short ternary above, it checks specifically for null/undefined rather than any falsy value, so 0 or '' pass through untouched instead of triggering the fallback.

Example: Null Coalescing Operator

php
<?php
$value = 0;
echo $value ?? "fallback";
?>

Direct Output with Ternary

Because the ternary operator is itself an expression with a value, you can drop it directly inside an echo call — echo $loggedIn ? 'Welcome back' : 'Please log in'; — without needing a separate variable to hold the chosen string first.

Example: Direct Output with Ternary

php
<?php
$loggedIn = true;
echo $loggedIn ? 'Welcome back' : 'Please log in';
?>

Nested Ternary Operators

Nesting one ternary inside another lets you express a short chain of choices in a single line, but readability drops fast past two levels. Past that point, a match expression or a plain if/elseif chain almost always communicates the same logic more clearly.

Example: Nested Ternary Operators

php
<?php
$score = 75;
$grade = $score >= 90 ? "A" : ($score >= 70 ? "B" : "C");
echo $grade;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.