PHP ternary operator
In this article, we will understand about a PHP ternary operator with the help of various examples.
What do you mean by Ternary operator?
It is also called a conditional operator. The ternary operator is an operator that decreases the length of code while performing comparisons. It is an alternative for using if-else and nested if-else statements. We can use the ternary operator when there is a need to simplify the if-else statements and to make efficient code out of a complex program structure.
Syntax:
Following is the syntax of ternary operator in php.
In the above syntax,
- Condition statement: It is a PHP expression that will be evaluated in order to return a Boolean value.
- code1: This will be the statement that will be executed when the conditional results will return true.
- code2: This will be the statement that will be executed when the conditional results will return in a false state.
Flow diagram of PHP:
Example 1:
Explanation:
In the above example, we have taken a condition that if the condition is true then the 20 value is displayed otherwise the 5 value is displayed.
Output:
Following is the output of this example:
Example 2:
Explanation:
In the above example, we have taken a condition that if the condition is true then the passed message is displayed otherwise the fail message is displayed.
Output:
Following is the output of this example:
Example 3:
Explanation:
In the above example, we have taken a condition that if the age is greater, the adult message is displayed otherwise the not adult message is displayed.
Output:
Following is the output of this example:
Example 4:
Explanation:
In the above example, we have taken a condition that if the condition is true, the eligible for credit card message is displayed otherwise the Not eligible for credit card is displayed.
Output:
Following is the output of this example: