← Back to Chapters

PHP Ternary Operator

? PHP Ternary Operator

? Quick Overview

The ternary operator in PHP is a shorthand way to write a simple if...else statement. It evaluates a condition and returns one of two values depending on whether the condition is true or false.

? Key Concepts

  • It replaces simple if...else statements.
  • It always evaluates a condition.
  • It returns exactly one value.

⚙️ Syntax / Theory

? View Code Example
// Basic ternary operator syntax in PHP
condition ? value_if_true : value_if_false;

? Code Example

? View Code Example
// Check age and assign message using ternary operator
<?php
$age = 20;
$message = ($age >= 18) ? "You are an adult." : "You are a minor.";
echo $message;
?>

? Live Output / Explanation

Output

You are an adult.

The condition $age >= 18 is evaluated. Since it is true, the value You are an adult. is returned and stored in $message.

? Interactive Playground

Test the logic live! Enter an age to see the ternary result:

Code Logic: ($age >= 18) ? "Adult" : "Minor"

Result: Adult

? Interactive Example

Change the number below to see how a ternary-style condition works (JavaScript simulation):

? View Code Example
// JavaScript simulation of ternary logic
const number = 7;
const result = (number % 2 === 0) ? "Even Number" : "Odd Number";
console.log(result);

? Use Cases

  • Assigning values based on a condition.
  • Displaying short conditional messages.
  • Inline conditional rendering.

✅ Tips & Best Practices

  • Use the ternary operator for short and clear conditions.
  • Always use parentheses for better readability.
  • Avoid deeply nested ternary expressions.

? Try It Yourself

  • Create a file ternary.php.
  • Check if a number is even or odd using a ternary operator.
  • Experiment with different conditions and outputs.