Conditional Operators : PHP



PHP Conditional Operators :

Syntax of the conditional operator is like –

condition ? true value : false value

Example : Conditional Operators

<html>
<head><title>Conditional Operators</title><head>
<body>
<?php
    $num1 = 10;
    $num2 = 20;
    
    $res = ($num1 > $num2) ? $num1 :$num2;
    echo "Test 1 : greater number is $res <br/>";
	
    $res = ($num1 < $num2) ? $num1 :$num2;
    echo "Test 2 : smaller number is $res <br/>";
    
?>
</body>
</html>

Output :

Test 1 : greater number is 20 
Test 2 : smaller number is 10 

Explanation :

$res = ($num1 > $num2) ? $num1 :$num2;

In this case if the value of num1 and num2 is 10,20 respectively. So following condition becomes false –

($num1 > $num2)

thus value after colon (:) will be assiged to the variable res.