Account
Categories

Ternary Operator


It is a special operator in PHP, and its symbol is the question mark ?.

The name itself shows its meaning — ternary means three parts.

It contains three parts, of which the first part is:

  • Condition – This part holds the condition that decides which expression will run.
  • Expression 1 → When the condition meets the expression 1, and then the condition is found to be true, then this part immediately runs and shows the result in the browser.
  • Expression 2 → If the condition does not find the true, then this part runs in the browser.

It makes the ternary operator a smoother and simpler way to write conditions. It works in the same way as the if-else and is also known as the conditional operator.

Syntax:

$variable = (condition)? value_if_true : value_if_false;

Example:

$age = 20;  
$result = ($age >= 18) ? "Adult": "Minor";  
echo $result;

Output:

Adult