![]() |
VOOZH | about |
If-else and Switch cases are used to evaluate conditions and decide the flow of a program. The ternary operator is a shortcut operator used for shortening the conditional statements.
ternary operator: The ternary operator (?:) is a conditional operator used to perform a simple comparison or check on a condition having simple statements. It decreases the length of the code performing conditional operations. The order of operation of this operator is from left to right. It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows.
Syntax:
(Condition) ? (Statement1) : (Statement2);
The result of this comparison can also be assigned to a variable using the assignment operator. The syntax is as follows:
Variable = (Condition) ? (Statement1) : (Statement2);
If the statement executed depending on the condition returns any value, it will be assigned to the variable.
Advantages of Ternary Operator: Following are some advantages of ternary operator:
Example 1: In this example, if the value of $a is greater than 15, then 20 will be returned and will be assigned to $b, else 5 will be returned and assigned to $b.
Output:
Value of b is 5
Example 2: In this example, if the value of $age is more than or equal to 18, "Adult" is passed to print function and printed, else "Not Adult" is passed and printed.
Output:
Adult
When we use ternary operator: We use the ternary operator when we need to simplify the if-else statements that are simply assigning values to variables depending on a condition. An advantage of using a ternary operator is that it reduces the huge if-else block to a single line, improving the code readability and simplify it. Very useful while assigning variables after form submission.
Example:
Original Code:
Reduced to the following: Thus, the ternary operator successfully reduces the if-else block to a single line, hence serving its purpose.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.