PHP

❓ Ternary Operator in PHP

Ternary Operator (? :) is a shorthand conditional operator in PHP that simplifies basic if-else structures. It allows developers to evaluate expressions inline and assign values based on condition outcomes in a single line of code.

  • Key Concept: The syntax follows condition ? value_if_true : value_if_false. PHP 5.3+ also supports the short ternary syntax expr1 ?: expr2, which returns expr1 if it evaluates to true.

🛠️ Basic Syntax vs. Standard If-Else

The main advantage of the ternary operator is writing cleaner, more readable inline statements:

PHP
// Standard if-else structure
$isLoggedIn = true;

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

// Equivalent Ternary Operator structure
$message = $isLoggedIn ? "Welcome back!" : "Please log in.";
echo $message; // Outputs: Welcome back!

🔍 Practical Ternary Operator Examples

1️⃣ Inline HTML & Dynamic Output
Directly evaluate conditions inside HTML attributes or output strings.

PHP
$score = 85;
$result = ($score >= 50) ? "Passed" : "Failed";

echo "Student Status: " . $result; 
// Outputs: Student Status: Passed

2️⃣ Short Ternary Syntax (Elvish Operator)
If the true expression is omitted (expr1 ?: expr2), PHP returns expr1 if it evaluates to true (non-empty/non-zero), otherwise it returns expr2.

PHP
$input = "Custom Title";
$title = $input ?: "Default Title";

echo $title; // Outputs: Custom Title

$emptyInput = "";
$defaultTitle = $emptyInput ?: "Default Title";

echo $defaultTitle; // Outputs: Default Title

3️⃣ Nested Ternary Operations
You can chain ternary operators for multiple conditions, though parentheses are recommended for clarity.

PHP
$grade = 92;

$rating = ($grade >= 90) ? "Excellent" :
          (($grade >= 75) ? "Good" : "Needs Improvement");

echo $rating; // Outputs: Excellent

📊 Ternary Syntax Reference Table

Type Syntax Behavior Example
Standard Ternary $a ? $b : $c Returns $b if $a is true, otherwise returns $c. $x > 5 ? "Yes" : "No"
Short Ternary $a ?: $b Returns $a if $a evaluates to true, otherwise returns $b. $user ?: "Guest"
  • 📝 Short Summary

  • Use ternary operators to replace single if-else blocks to keep code concise.
  • Avoid deeply nested ternary operators as they can reduce code readability and maintainability.
  • For checking variable existence without warnings, consider using Null Coalescing (??) instead.