Conditional Operator


There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax:

 

Operator Description Example
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

 

PHP Conditional Operator Example

<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?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<br/>";
    /* If condition is true then assign a to result otheriwse b */
    $result = ($a < $b ) ? $a :$b;
    echo "TEST2 : Value of result is $result<br/>";
?>
</body>
</html>

This will produce following result

TEST1 : Value of result is 20
TEST2 : Value of result is 10

 

 

 

 

Leave a comment