Friday, February 19, 2010

Using The Tenary Operator in PHP

The tenary operator provides a more concise way to structure conditional statements. Instead of if-else or case statements, you could write it as follows:
(condition) ? value1 : value2
The condition in parentheses is evaluated; if it is true, the first value will be returned (value1). If the condition is false, value2 is returned. Because the tenary operator returns a value, the entire structure is often used to assign a value to a variable or used as an argument for a function. For example, in PHP the line below will print out SET or NOT SET, depending upon the status of the variable $var.
echo (isset($var)) ? 'SET' : 'NOT SET';
Another example of using the tenary operator would be to alternate the background colors on table rows. Here is an example:
$bg = '#eeeeee'; //set the initial background color
$bg = ($bg == '#eeeeee' ? '#ffffff' : '#eeeeee'); //switch the background color
echo '
Here the initial row background color is assigned to the variable $bg and then the tenary operation, alternating colors, is assigned back into $bg. The result is a table with rows of alternating background colors.

No comments:

Post a Comment

Get your own Widget