My Stuff
Username

Password

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


The Ternary Operator


Your rating: None Average: 5 (1 vote)

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:

<?
$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.

<?
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> &nbsp; </td></tr>\n";
}
 
echo "</table>";
?>

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can use BBCode tags in the text.
  • You can enable syntax highlighting of source code with the following tags: [code], [blockcode], [asp], [awk], [c], [cpp], [csharp], [drupal5], [drupal6], [java], [javascript], [jquery], [mysql], [perl], [perl6], [php], [python], [ruby], [sql], [vb], [vbnet], [xml].
  • Use to create page breaks.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.