Skip to content

PHP Tutorial Conditional Statements

Ternary Operator

Lesson 86 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

The ternary operator is a compact if ... else that gives back a value. It has three parts, which is where the name comes from.

Text
PLAIN
condition ? value_if_true : value_if_false
index.php
PHP
<?php
$age = 20;

$label = $age >= 18 ? "Adult" : "Minor";

echo $label;
Output
OUTPUT
Adult

This does the same as:

index.php
PHP
if ($age >= 18) {
    $label = "Adult";
} else {
    $label = "Minor";
}

Where it shines

Choosing one of two values, especially inside a string or template.

index.php
PHP
<?php
$items = 1;

echo "You have $items " . ($items === 1 ? "item" : "items") . " in your cart.";
Output
OUTPUT
You have 1 item in your cart.
index.php
PHP
<?php
$isActive = true;
?>
<span class="status <?= $isActive ? 'on' : 'off' ?>"><?= $isActive ? 'Active' : 'Inactive' ?></span>
Output
OUTPUT
<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.

index.php
PHP
<?php
$count = 3;

echo "Total: " . ($count > 1 ? "many" : "one");
Output
OUTPUT
Total: many

Do not nest ternaries

Since PHP 8, nesting without brackets is an error. Even with brackets it is hard to read.

index.php
PHP
<?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;
Output
OUTPUT
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.

lightbulb
One question, two answers
If you can say it as “this or that, depending on one condition”, a ternary fits. Anything more complicated deserves an if or a match.