In PHP, the ternary operator (? :
) is a shorthand way of writing a simple if-else statement. It allows you to write a conditional expression and choose one of two values based on whether the condition is true or false. Here’s the basic syntax of the ternary operator:
condition ? value_if_true : value_if_false;
Here’s how you can use the ternary operator in PHP:
$condition = true; // Replace with your actual condition
// Using the ternary operator
$result = $condition ? "Value if true" : "Value if false";
echo $result;
In this example, if the condition is true
, the value "Value if true"
will be assigned to the variable $result
. If the condition is false
, the value "Value if false"
will be assigned.
Here’s a practical example:
$age = 25;
$isAdult = $age >= 18 ? "Yes, it's an adult" : "No, it's not an adult";
echo $isAdult;
In this example, if the $age
is greater than or equal to 18, it will output “Yes, it’s an adult.” Otherwise, it will output “No, it’s not an adult.”
The ternary operator is useful for simplifying conditional assignments when you have a straightforward if-else scenario. However, for more complex conditions or when you need multiple branches, it’s usually better to use traditional if-else statements for better readability.