PHP Shorthand If and Ternary Operators

Choose between full ternary, short ternary and null coalescing without losing valid zero or empty values.

Lesson 30 of 86Beginner10 min read

A ternary expression chooses one of two values using a condition. Instead of writing an if statement just to assign a label, you can write $label = $paid ? 'Paid' : 'Pending';. This is useful when the decision is short and both possible results are easy to understand. It becomes harder to read when the condition or either result contains several operations.

PHP also has the short ternary operator ?:, the null coalescing operator ??, and an alternative if: ... endif; syntax often used in templates. They solve related but different problems. This guide separates those cases so you can choose defaults without accidentally discarding valid values such as zero.

Full ternary syntax

The full form is condition ? valueWhenTrue : valueWhenFalse. PHP evaluates the condition as a boolean and evaluates only the selected result expression. The whole ternary produces a value, so it can be assigned, returned or passed as an argument. An if statement instead controls which statements run.

Use the full form for a simple two-way choice: paid versus pending, enabled versus disabled, or a small fee selected by a clear rule. Name a complicated condition before using it. For example, $eligibleForDiscount is easier to interpret than a long mixture of age, account and order checks inside the ternary.

Do not use a ternary merely to squeeze multiple actions onto one line. A branch that logs an event, changes a record and sends a response deserves an ordinary if block. The best shorthand removes repetitive structure while preserving the decision. It should not make the reader search through punctuation to discover the application's behavior.

Short ternary means a truthy fallback

The short form $value ?: $fallback returns $value when it is truthy and otherwise returns the fallback. The value is evaluated once. This is convenient when empty-like values should all produce the same default, such as replacing an empty display label with a placeholder.

PHP treats several values as false in a boolean context, including false, null, zero, an empty string, the string '0' and an empty array. Therefore, ?: is not a general test for missing data. If zero is a legitimate count or '0' is a legitimate field value, the short ternary can replace it unexpectedly.

By contrast, $value ?? $fallback uses the fallback for an undefined or null value. It preserves false, zero and empty strings. When accessing a possibly absent array key, null coalescing also avoids an undefined-key warning. Short ternary still evaluates its left expression normally, so reading an absent key before applying ?: can produce a warning.

Parentheses and nested decisions

Nested ternaries are often difficult to read because the question and its results become separated by more punctuation. In PHP 8, unparenthesized chains of full ternary expressions are rejected. If nesting is necessary, write explicit parentheses so the grouping is visible. For three or more named alternatives, consider match or an ordinary sequence of conditions instead.

Operator precedence also matters when concatenating a ternary result into text. Write 'Status: ' . ($paid ? 'Paid' : 'Pending'). The parentheses make the intended grouping obvious and protect the expression from mistaken assumptions. Do not rely on readers remembering the relative precedence of every operator in a line.

Only the selected branch is evaluated. That allows a fallback expression to be expensive without being run every time, but it can also conceal side effects. Prefer branches that calculate values. When a branch performs a visible action such as saving data, use a statement structure that makes the action easy to find during review.

Alternative if syntax in templates

PHP supports if ($condition):, followed by content, then endif;. It also supports elseif: and else:. This syntax is useful when PHP surrounds HTML because the closing endif clearly names the structure being closed. It is still a full if statement, not a ternary expression, and it can contain several statements.

Keep one style consistent within a block. Do not begin with a colon and end with a brace. When printing user-controlled text in an HTML template, escape it for HTML regardless of which condition syntax you choose. Shorter control flow does not change output security requirements. The PHP comparison operators reference documents ternary behavior and its PHP 8 associativity changes.

PHP Shorthand If and Ternary Operators Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Select one label

The first condition is false, so the second label is selected. The second condition is true, so shipping becomes zero. Neither example changes the source values. The expressions simply calculate results from information already available. A real checkout should calculate prices on the server using validated order data.

PHP
<?php
$paid = false;
$label = $paid ? 'Paid' : 'Pending';
echo $label . PHP_EOL;

$quantity = 4;
$shipping = $quantity >= 3 ? 0 : 5;
echo 'Shipping: ' . $shipping . PHP_EOL;
Output
Pending
Shipping: 0
Example 2

Preserve a legitimate zero

The first line treats zero as false and replaces it. The second line preserves zero because the key exists and its value is not null. The last line supplies a default for an absent key. These are different policies, and neither operator can decide the correct policy for your application without a clear requirement.

PHP
<?php
$settings = ['retries' => 0];
echo ($settings['retries'] ?: 3) . PHP_EOL;
echo ($settings['retries'] ?? 3) . PHP_EOL;
echo ($settings['timeout'] ?? 10) . PHP_EOL;
Output
3
0
10

PHP Shorthand If and Ternary Operators in Real Projects

Practical task: show an inventory message

An inventory screen must show Out of stock for zero units and Available: N for a positive count. The count is a trusted nonnegative integer. Use a full ternary because the two results depend on a specific comparison, rather than treating every false-like value as equivalent. Keep the message generation separate from any later HTML escaping.

PHP
<?php
function stockMessage(int $stock): string {
    if ($stock < 0) {
        throw new InvalidArgumentException('Stock cannot be negative');
    }
    return $stock === 0 ? 'Out of stock' : 'Available: ' . $stock;
}

echo stockMessage(0) . PHP_EOL;
echo stockMessage(7) . PHP_EOL;
Output
Out of stock
Available: 7

The early if protects the function's domain. The ternary then handles two valid states. Try adding a low-stock category for one or two units. At that point, a clear if sequence may communicate the three ranges better than a nested ternary. The exercise is about choosing a readable representation, not maximizing the number of shorthand operators.

PHP Shorthand If and Ternary Operators FAQ

Is a ternary faster than if?

Do not choose it for a presumed performance gain. Choose it when a short expression makes one result easier to understand. Measure real bottlenecks rather than optimizing punctuation.

What does the Elvis operator mean?

That nickname commonly refers to ?:. In PHP it returns the left value if truthy and otherwise the fallback. It is not the same as ??.

Can I use a ternary to return an array?

Yes. Either result can be an expression, including an array. If both arrays are large, assign or return them in clear blocks instead.

Why did my zero become a default?

You probably used ?:, which treats zero as false. Use a specific comparison or ?? when zero must survive.

When should I avoid nested ternaries?

Avoid them when a reader must mentally untangle several decisions. Named conditions, if blocks and match can each express the rule more plainly.

PHP Shorthand If and Ternary Operators Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which expression clearly prefixes a chosen status with text?

PHP Shorthand If and Ternary Operators Quiz

2 questions to check what you learned.

  1. What does $paid ? 'Paid' : 'Pending' produce when $paid is false?

    • Paid
    • Both strings
    • Pending
  2. Which operator preserves an existing value of zero while supplying a default for null?

    • ??
    • ?:
    • ++