» The Ternary Operator by sde |
|
(Login to remove green text ads)
The Ternary Operator is a comparison operator commonly found in C-Style languages including PHP. It can end up saving you a bit of time and lines of code, so I thought I would show you.
Here is the Format: ( expr1 ) ? ( expr2 ) : (expr3)
If expr1 is true, then it evaluates to ( expr2 )
If expr1 is false, then it evaluates to ( expr3 )
Here is a Code Example:
PHP Code:
<?
$action = "edit";
// first i will show you an if/else statement
// then the equivalent using the ternary operator.
// example 1: If/Else without the Ternary Operator
if( $action == "edit" )
{
$text = "the action equals edit";
}
else
{
$text = "the action does not equal edit";
}
echo $text . "<br><br>\n\n";
// example 2: Same test and assignment using the Ternary Operator
$text = ( $action == "edit" ) ? "the action equals edit" : "the action does not equal edit";
echo $text;
?>
Both of these examples do the exact same things, but the ternary operator will just save you a bit of code.
The example above isn't that exciting so I will include one more which will demonstate a little more functionality. This is how I might use the ternary operator in use with alternating table background color for every other row.
PHP Code:
<?
echo "<table border=0 cellspacing=0 cellpadding=0 width=500>";
for($i=0;$i<20;$i++)
{
// assign color using the Ternary Operator
$color = ( $i % 2 == 0 ) ? '#CCCCCC' : '#FF0000';
echo "<tr height=10 bgcolor=$color><td> </td></tr>\n";
}
echo "</table>";
?>
|
|