Posted by : Chris London in (Programming, Tutorial)

Ternary Operators

Tagged Under : , , ,

If you don’t know what ternary operators are then you are missing out! The day I learned about ternary operators I nearly passed out. There are so many wasted lines of code if you don’t know about them. This is what a standard if ... else ... statement looks like using C, Obj-C, C++, C#, Java, or JavaScript:

if (apples > oranges) {
     fruit = apples;
} else {
     fruit = oranges;
}

Here is the same code but in ternary operator form:

fruit = apples > oranges ? apples : oranges;

As you can see, ternary operators save a lot of lines, time, and space. However, finding a situation to use ternary operators is not always easy.

Here is the syntax for a ternary operator:

condition ? if true : if false

Let’s take a look at a real world HTML/PHP example. It’s a very common scenario where we create a table of data on a website but we want the even rows to have the CSS class “evenRow” and we want the odd rows to have the CSS class “oddRow”:

<table>
   <?php for ($i = 0; $i < 10; $i++) { ?>
      <tr class='
         <?php
            if ($i % 2 == 0) // if $i is an even number
            {
               echo 'evenRow';
            }
            else
            {
               echo 'oddRow';
            }
         ?>
      '>
         <td>data</td>
      </tr>
   <?php } ?>
</table>

As we can see there are plenty of lines of code. For those of you who don’t know what the modulus (%) does, it returns the remainder of a division. For example 2 / 1 = 2 and 2 % 1 = 0 because there is nothing left over after you divide it. If we were to flip it around we get 1 / 2 = 0.5 and 1 % 2 = 1 because when you divide 1 by 2 you get a remainder of 1. So when we loop through 1 to 10 we get:

  • 1 % 2 = 1
  • 2 % 2 = 0
  • 3 % 2 = 1
  • 4 % 2 = 0, etc.

Here’s the same example but using ternary operators:

<table>
   <?php for ($i = 0; $i < 10; $i++) { ?>
      <tr class='
         <?php echo ($i % 2 == 0 ? 'evenRow' : 'oddRow'); ?>
      '>
         <td>data</td>
      </tr>
   <?php } ?>
</table>

I find the ternary operator code to be much more clean looking.

NOTE: There isn’t any performance advantage to using a ternary operator. It’s main benefit is less lines of code and a cleaner look.

Here’s another real world example in PHP where if the number of kitties = 1 then it echo’s a ‘y’ otherwise it echo’s an ‘ies’:

You have <?php echo $kitties;?> kitt<?php echo ($kitties == 1 ? 'y' : 'ies')?>

Some people may be tempted to do $kitties > 1 but this would result in “You have 0 kitty” if $kitties == 0. I’m not an English major but I’m pretty sure it’s “You have 0 kitties”. Anyone know why the zero quantity is pluralized?

Where to Put the Parentheses?

I haven’t tested C++ to see if different parenthesis placement is valid or not but the following are valid in PHP:

No parentheses

$result = $apples > $oranges ? $apples : $oranges;

Conditional parentheses

$result = ($apples > $oranges) ? $apples : $oranges;

Complete parentheses (my personal favorite)

$result = ($apples > $oranges ? $apples : $oranges);

Overboard parentheses (too many in my opinion)

$result = (($apples > $oranges) ? $apples : $oranges);

You can place ternary operators just about anywhere in your code. They can be a part of complex algorithms or just about anything else. I do, however, recommend against their overuse. Ternary operators are best when they appear on their own line.

Nested Ternary Operators

Yes you can have nested ternary operators but if you feel like you need one then there’s probably a better way to program it. I remember using one once and at the time I was pretty sure that it was the best way to do it. Now that I’m older I’m sure I could’ve found a better way to do it using a switch statement or elseif statement or something else.

Here’s an example of a nested ternary operator. This is by no means the best way to accomplish the same end result:

$fruit = ($apples > $oranges ? $apples : ($oranges > $papaya ? $oranges : $papaya));

So what this does is if you have more apples than oranges then it will return apples. If you don’t then it checks if you have more oranges than papayas. If you do it returns oranges otherwise it returns papayas. This is also an example of why I prefer the method of parentheses that I do. You can easily see which ternary operators are clumped together where as other peoples’ favorite is a little more difficult:

$fruit = ($apples > $oranges) ? $apples : ($oranges > $papaya) ? $oranges : $papaya;

Anyway, I hope I didn’t lose any of you along the way. Leave a comment if something was confusing or you know of a better way to accomplish these things

Share and Enjoy:
  • Facebook
  • Twitter
  • Add to favorites
  • email
  • Google Bookmarks

Comments:

Make a comment