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.
if...else statements.
// Basic ternary operator syntax in PHP
condition ? value_if_true : value_if_false;
// Check age and assign message using ternary operator
<?php
$age = 20;
$message = ($age >= 18) ? "You are an adult." : "You are a minor.";
echo $message;
?>
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.
Test the logic live! Enter an age to see the ternary result:
Code Logic: ($age >= 18) ? "Adult" : "Minor"
Result: Adult
Change the number below to see how a ternary-style condition works (JavaScript simulation):
// JavaScript simulation of ternary logic
const number = 7;
const result = (number % 2 === 0) ? "Even Number" : "Odd Number";
console.log(result);
ternary.php.