Ternary Operator in PHP
The ternary operator in PHP provides a one-line approach to representing a simple conditional statement. We commonly use it as a shorthand method for if-else statement which makes the code much more simple, concise and readable.
The ternary operator allows you to write a single line of code instead of a block of if-else statements. In certain cases, it improves readability by reducing code clutter.
This operator is also known as the conditional operator because it evaluates a condition and returns one of two values based on whether the condition is true or false.
Syntax of Ternary Operator in PHP
The ternary operator (?:) normally takes three operands. The basic syntax of the ternary operator in PHP language is as follows:
$variable = exp1 ? exp2 : exp3;
In the above syntax, exp1, exp2, and exp3 are expressions. The exp1 is the condition that evaluates to true or false. If it comes true, the expression exp2 will evaluate and the value of exp2 will store in the $variable. If exp1 is false, exp3 will evaluate and its value will store in the $variable.
Consider a simple example to get familiar with the syntax.
Example 1:
<?php
$x = 20;
$y = 10;
$z = $x > $y ? 20 : 10;
echo $z;
?>
Output: 20
In the above code, the first ($x > $y) is evaluated. If it is true, the value of variable $x is stored in the variable $z. If it is false, the value of variable $y is stored in the variable $z.
Here, ($x > $y) is true because the value of $x is greater than the value of $y. Therefore, the value of $x will assign in the variable $z and display on the console or browser. Look at the below figure.
As you can see in the above example, we have used three operands (or expressions), such as ($x > $y), 20, and 10. That’s why it is called a ternary operator in PHP.
Here’s the equivalent of the ternary operator code using an if-else statement:
<?php
$x = 20;
$y = 10;
if ($x > $y) {
$z = 20;
} else {
$z = 10;
}
echo $z;
?>
With if-else statement, the condition ($x > $y) is checked. If it’s true, $z is assigned the value 20. Otherwise, it is assigned 10 to the $z, just like in the ternary operator.
As you can see that we have achieved the same result. However, the ternary operator is more concise. If your conditional expression is complex, it’s advisable to you to use the if-else statement because it provides better readability. I think you understood that when to use the ternary operator in PHP program and when to opt for if-else statements.
Basic Examples of Ternary Operator
Let’s take some basic examples based on the using of PHP ternary operator.
Example 2:
<?php
$age = 20;
$status = ($age >= 18) ? 'Adult' : 'Minor';
echo $status;
?>
Output: Adult
In this example, the condition checks if $age is 18 or older. If true, $status is assigned the value ‘Adult’. If it is false, $status is assigned ‘Minor’.
You can also use the ternary operator directly inside echo statement to dynamically display content based on a condition.
Example 3:
<?php
$is_logged_in = true;
echo ($is_logged_in) ? 'Welcome back!' : 'Please log in.';
?>
Output: Welcome back!
Chained Ternary Operators
You can create chained ternary operators which allows to evaluate multiple conditions in a single line of code. However, it can affect the readability of the code.
Example 4:
<?php
$grade = 85;
$status = ($grade >= 90) ? 'A' :
(($grade >= 80) ? 'B' :
(($grade >= 70) ? 'C' : 'F'));
echo $status;
?>
Output: B
Nested Ternary Operators
A nested ternary operator in PHP allows you to place one ternary operator inside another. It is usually to create more complex conditions. Therefore, nested ternary operators can make code harder to read, so it’s advisable you to use them sparingly.
Let’s take a simple example in which we will place one ternary operator inside another to make a complex condition.
Example 5:
<?php
$score = 45;
$result = ($score >= 50) ? 'Pass' : (($score < 50 && $score >= 40) ? 'Retake' : 'Fail');
echo $result;
?>
Output: Retake
Advanced Examples of Ternary Operator
Let’s take an example in which we will use the ternary operator in a function.
Example 6:
<?php
function checkUserStatus($is_active) {
return $is_active ? 'Active User' : 'Inactive User';
}
echo checkUserStatus(true); // passing argument to function.
?>
Output: Active User
In this example, we have used the ternary operator inside the function that returns a value based on the function argument.
Example 7:
<?php
$x = 20;
$y = 20;
++$x;
$y--;
$z = $x < $y ? $x : $y;
echo $z;
?>
Output: 19
Example 8:
<?php
$x = 2;
$y = 4;
$z = ++$x < $y-- - 1 ? $x : $y;
echo $z;
?>
Output: 3
Best Practices for Using Ternary Operator
Here, we have explained some key points to use ternary or conditional operator in PHP that you should remember.
- Use ternary operator for a simple condition that contains only two alternatives. One for when the condition is true, and one for when the condition is false.
- Always ensure your code is readable.
- Avoid using it if it becomes hard to understand.
- Avoid overusing ternary operators, especially when chaining or nesting them, because they can make your code difficult to debug.
- Avoid chaining too many ternary operators together because they can make confusing code.
When Not to Use Ternary Operator
There are some situations where using the ternary operator is not appropriate. They are as:
- If you have complex conditions, use an if-else statement which is more readable.
- If you need to execute more than one statement based on a condition, it’s better to use an if-else structure.
In this tutorial, we have explained the ternary operator in PHP, which is a powerful and concise way to create a simple conditional statement. By using it carefully, you can make your code cleaner and more efficient. However, when the conditions become complex, they can be difficult to read, but is useful if you deal with only two alternatives and want to write compact code.