Section 6.9. The Ternary Operator


6.9. The Ternary Operator

The ternary operator is so named because it is the only operator that takes three operands: a condition, a result for true, and a result for false. If that sounds like an if statement to you, you are right on the moneythe ternary operator is a shorthand (albeit very hard to read) way of doing if statements. Here's an example:

     $agestr = ($age < 16) ? 'child' : 'adult'; 

First there is a condition ($age < 16), then there is a question mark, and then a true result, a colon, and a false result. If $age is less than 16, $agestr will be set to 'child'; otherwise, it will be set to 'adult'. That one-liner ternary statement can be expressed in a normal if statement like this:

     if ($age < 16) {             $agestr = 'child';     } else {             $agestr = 'adult';     }

So, in essence, using the ternary operator allows you to compact five lines of code into one, at the expense of some readability.

You can nest ternary operators by adding further conditions into either the true or the false operands. For example:

     $population = 400000;     $city_size =             $population < 30 ? "hamlet"               : ($population < 1000 ? "village"               : ($population < 10000 ? "town"               : "city"))             ;     print $city_size;

In that example, PHP first checks whether $population is less than 30. If it is, then $city_size is set to hamlet; if not, then PHP checks whether $population is less than 1000. Note that an extra parenthesis is placed before the second check, so that PHP correctly groups the remainder of the statement as part of the "$population is not less than 30" block. Finally, if $population is not less than 10,000, $city_size is set to "city," with no further checks. At this point, you need to close the parentheses you have opened inside the stacked conditions.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net