The Ternary Operator


Believe it or not, there's an operator that acts just like an if statement, the ternary operator. This operator has an unusual form; just ?:. Here's how you use it:

 $result = condition ? expression1 : expression2; 

If condition is true, then expression1 is assigned to $result; otherwise, expression2 is assigned to it instead. This can lead to some pretty compact statements. For example, take a look at this script from the previous "Using else Statements" section:

 $temperature = 26; if ($temperature > 75 && $temperature < 80) {     echo "We're in the comfort zone."; } else {     echo "We're outside the comfort zone."; } 

All six lines of the if statement can be condensed into a single line using the ternary operator (note that this statement is too long for a single line in the book, so I'm cutting it up onto two lines):

 $temperature = 26; echo $temperature > 75 && $temperature < 80 ? "We're in the comfort zone." :      "We're outside the comfort zone."; 

Here's another example, which finds the absolute value of numbers (note that this example uses the - negation operator to reverse the sign of numbers if needed):

 <?php     $value = -25;     $abs_value = $value < 0 ? -$value : $value;     echo $abs_value; ?> 

The following example is a little more complex; it converts decimal numbers to hexadecimal (base 16) as long as they will fit into a single hexadecimal digit. It uses the PHP chr function (see Chapter 3) to convert numbers to ASCII characters:

 <?php     $value = 14;     $output = $value < 10 ? "0x" . $value : "0x" . chr($value - 10 + 65);     echo "In hexadecimal, $value = $output."; ?> 

This script provides this result: In hexadecimal, 14 = 0xE.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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