Conditional Operator in PHP
In this article, we will see the conditional operator in php.
Conditional operator( ? 🙂 : It is the only ternary operator; which accepts 3 operands.
(operand1) ? operand2: operand3;
operand1: should be a condition
operand2: if the condition is true, operand2 is executing
operand3: if the condition is false, operand3 is executing
<?php $num = 10; $result=(($num%2)==0) ? "even" : "odd"; echo $num, "is", $result, "number"; /* ouput: 10 is even number ?>
Note: Conditional operator is a kind of shorthand notation for if else statement.
- In the above code, we have created a “num” variable and assigned the value “10”.
- We pass the “($num%2)==0)” condition to operand1.
- Then we give the “even” value to operand2 and the “odd” value to operand3.
- If the operand1 condition is true, the operand2 value is displayed else the operand3 value is displayed.
- Here, the condition is true. So, it returns “even“.