How to Use the Ternary Operator in PHP

The PHP ternary operator is a shorthand comparison operator that allows you to write cleaner and more concise if-else statements. This article explains the syntax of the PHP ternary operator, provides practical examples of how to implement it, and covers shorthand alternatives to help you write more readable code.

Understanding the Ternary Operator Syntax

The ternary operator gets its name because it takes three operands: a condition, a result for true, and a result for false. It is represented by a question mark ? and a colon :.

Here is the basic syntax:

$result = (condition) ? value_if_true : value_if_false;

How it works: 1. The condition is evaluated first. 2. If the condition evaluates to true, the expression returns value_if_true. 3. If the condition evaluates to false, the expression returns value_if_false.


Basic Implementation Example

Consider a standard if-else statement that determines if a user is logged in:

if ($is_logged_in) {
    $message = "Welcome back!";
} else {
    $message = "Please log in.";
}

Using the ternary operator, you can compress these five lines of code into a single line:

$message = $is_logged_in ? "Welcome back!" : "Please log in.";

Shorthand Ternary Operator (The Elvis Operator)

Since PHP 5.3, you can exclude the middle part of the ternary operator. This is commonly referred to as the “Elvis operator” (?:). It returns the first expression if it evaluates to true (or is truthy); otherwise, it returns the second expression.

$username = $input_username ?: 'Guest';

In this example, if $input_username is not empty (evaluates to true), $username will be assigned its value. If it is empty or null, $username will be assigned 'Guest'.


Nested Ternary Operators (Best Practices)

You can nest ternary operators to evaluate multiple conditions. However, nesting should be used sparingly because it can quickly make your code difficult to read.

$score = 85;

$grade = ($score >= 90) ? 'A' : (($score >= 80) ? 'B' : 'C');
echo $grade; // Outputs: B

Note: In PHP 7.4 and later, nested ternary operators require explicit parentheses to define the order of evaluation, as left-associativity without parentheses has been deprecated.

To keep your code maintainable, it is highly recommended to use standard if-else or switch statements instead of nesting ternary operators.