”;
You would use conditional operators in PHP when there is a need to set a value depending on conditions. It is also known as ternary operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.
Ternary operators offer a concise way to write conditional expressions. They consist of three parts: the condition, the value to be returned if the condition evaluates to true, and the value to be returned if the condition evaluates to false.
Operator | Description | Example |
---|---|---|
? : | Conditional Expression | If Condition is true ? Then value X : Otherwise value Y |
Syntax
The syntax is as follows −
condition ? value_if_true : value_if_false
Ternary operators are especially useful for shortening if-else statements into a single line. You can use a ternary operator to assign different values to a variable based on a condition without needing multiple lines of code. It can improve the readability of the code.
However, you should use ternary operators judiciously, else you will end up making the code too complex for others to understand.
Example
Try the following example to understand how the conditional operator works in PHP. Copy and paste the following PHP program in test.php file and keep it in your PHP Server”s document root and browse it using any browser.
<?php $a = 10; $b = 20; /* If condition is true then assign a to result otheriwse b */ $result = ($a > $b ) ? $a :$b; echo "TEST1 : Value of result is $result n"; /* If condition is true then assign a to result otheriwse b */ $result = ($a < $b ) ? $a :$b; echo "TEST2 : Value of result is $result"; ?>
It will produce the following output −
TEST1 : Value of result is 20 TEST2 : Value of result is 10
”;