### Conditional Operator

Posted:

**Thu Mar 27, 2008 10:38 pm**- Code: [Select all] [Expand/Collapse] [Download] (Untitled)
- General form:

exp1 ? exp2 : exp3;

exp1 is true - entire expression evaluates as exp2

exp1 is false - entire expression evaluates as exp3

Example 1:

The following will get the minimum of x and y

<?

$x = 10;

$y = 20;

$a = ($x < $y) ? $x : $y;

echo $a." is the minimum of the two numbers";

?>

Example 2:

The following will output the value of i 20 times

<?

$i = 0;

$char1 = " is less than or equal to 10<BR>";

$char2 = " is less than or equal to 20<BR>";

while ($i < 20) {

echo $i++ < 10 ? $i.$char1 : $i.$char2;

}

?>

Example 3:

The following will output "cat penguin forth fifth sixth"

<?

$i = 0;

$j = 2;

$x = array("dog", "cat", "penguin");

$y = array("first", "second", "third", "forth", "fifth", "sixth");

while ($i<5) {

$a = $i++<$j ? $x["$i"] : $y["$i"];

echo "$a<br>";

}

?>