The ternary operator in PHP is a shorthand way of writing an if
–else
statement. It has the following syntax:
$result = (condition) ? value_if_true : value_if_false;
Here’s an example of how to use the ternary operator:
$age = 25;
$can_drink = ($age >= 21) ? true : false;
// The same as:
if ($age >= 21) {
$can_drink = true;
} else {
$can_drink = false;
}
The ternary operator can also be nested:
$age = 25;
$status = ($age >= 21) ? 'adult' : (($age >= 18) ? 'teen' : 'child');
// The same as:
if ($age >= 21) {
$status = 'adult';
} else {
if ($age >= 18) {
$status = 'teen';
} else {
$status = 'child';
}
}
You should use the ternary operator sparingly, as it can make your code harder to read if overused. It is best suited for simple conditions with a clear and concise value for each branch. For more complex conditions, it is usually better to use a regular if
–else
statement.