What is the use of the ternary operator in PHP?
The ternary operator is a short way to write a simple if-else statement in one line. The syntax is condition ? value_if_true : value_if_false.
<?php
$age = 20;
$result = ($age >= 18) ? "Adult" : "Minor";
echo $result;
?>
Output:
Tutorials Class - Output Window
Adult
There is also a shorter form ?: (called Elvis operator). It returns the first value if it is not empty, otherwise the second one.
<?php
$username = "";
echo $username ?: "Guest";
?>
Output:
Tutorials Class - Output Window
Guest
Use it only for short and simple conditions. For long conditions a normal if-else is easier to read. More details in PHP Ternary Operator.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Operators |
| Exercises & Assignments |
|---|
| Write a PHP program to add two numbers |
| Write a PHP program to check whether a number is positive, negative or zero |