The ternary operator is a compact if ... else that gives back a value. It has three parts, which is where the name comes from.
condition ? value_if_true : value_if_false
<?php
$age = 20;
$label = $age >= 18 ? "Adult" : "Minor";
echo $label;
Adult
This does the same as:
if ($age >= 18) {
$label = "Adult";
} else {
$label = "Minor";
}
Where it shines
Choosing one of two values, especially inside a string or template.
<?php
$items = 1;
echo "You have $items " . ($items === 1 ? "item" : "items") . " in your cart.";
You have 1 item in your cart.
<?php
$isActive = true;
?>
<span class="status <?= $isActive ? 'on' : 'off' ?>"><?= $isActive ? 'Active' : 'Inactive' ?></span>
<span class="status on">Active</span>
Always use brackets in larger expressions
The ternary has a low priority, so when you mix it with . or other operators, wrap it in brackets.
<?php
$count = 3;
echo "Total: " . ($count > 1 ? "many" : "one");
Total: many
Do not nest ternaries
Since PHP 8, nesting without brackets is an error. Even with brackets it is hard to read.
<?php
$score = 72;
// Hard to read
$grade = $score >= 90 ? "A" : ($score >= 60 ? "C" : "F");
echo $grade . "\n";
// Much clearer
if ($score >= 90) {
$grade = "A";
} elseif ($score >= 60) {
$grade = "C";
} else {
$grade = "F";
}
echo $grade;
C
C
When not to use it
If either side needs several statements, or the line becomes longer than a screen, use a real if. The goal is shorter and clearer code.
One question, two answers
if or a match.