Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    php
  » The Ternary Operator
      by sde
 Page 1 of 1 
   

(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 == ) ? '#CCCCCC' '#FF0000';
  echo 
"<tr height=10 bgcolor=$color><td> &nbsp; </td></tr>\n";
}

echo 
"</table>";
?>





 
 Page 1 of 1 
   

Rate This Article
1 2 3 4 5 6 7 8 9 10





Copyright © 2000-2006, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting
Open Circle