Learning Ternary Operators — Tips & Tricks

By  on  

I started using ternary operator logic about six months ago and notice myself using shorthand if/else logic all the time. It shortens my code, the time to write it, and makes me look smarter to the mustaches.

Thanks to Google Analytics, I've found that I receive many page views from programmers looking for information on "shorthand if/else", "ternary logic", and "shorthand logic php". I've created a few guidelines for "?:" rookies to make learning shorthand if/else as quick and easy as it should be.

Start With If/Else, Then Convert To Ternary

Start with your expressions in simple if/else code, and then carefully convert each if/else into a shorter ternary statement. It may help to take the additional step of creating variables for each expression.

/* start with if / else ... */
if($language == 'php')
{
	$dynamic = true;
}
else
{
	$dynamic = false;
}

/* ... then convert */
$dynamic = ($language == 'php' ? true : false); //or 1 : 0

/* optional code shortening */
$dynamic = $language == 'php';

Use Parenthesis To Group Logic

Keeping your expressions in parentheses is a great way to keep your code organized for later maintenance.

//viva grouping!
$age_code = ($age > 10 ? ($age > 20 ? ($age > 30 ? 'senior' : 'adult') : 'teen') : 'youngster');

//the following isn't as fun to read
$age_code = $age > 10 ? $age > 20 ? $age > 30 ? 'senior' : 'adult' : 'teen' : 'youngster';

Use "Intermediate" Variables For Parts of the Expression

The above 10/20/30 code is rough and can be difficult to maintain. Using variables may help simplify things.

//better?
$over_30 = ($age > 30 ? 'senior' : 'adult');
$over_20 = ($age > 20 ? $over_30 : 'teen');
$age_code = ($age > 10 ? $over_20 : 'youngster');

Use True/False Boolean, Not Just The Expression

As you probably know, you can use JUST the expression as the return value. If you believe that will hurt you during the learning process, explicitly return true or false.

/* explicit */
$can_drive = ($age >= 16 ? true : false);

/* implicit, just the expression */
$can_drive = $age >= 16;

Know When Not To Use Ternary Logic

If there are many nested if/else statements in the logic, shorthand expressions may not be the best option. For example, the following snippet of code returns whether a given year is a leap year:

$is_leap_year = ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));

The above code works well for ternary logic because it wont have to be updated frequently -- the leap year "calculation" is always the same. If you have code that needs to be updated often, shorthand if/else may not be the optimal choice.

Test! Test! Test!

As with any type of programming, test early and often!

Recent Features

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

Incredible Demos

  • By
    Generate Dojo GFX Drawings from SVG Files

    One of the most awesome parts of the Dojo / Dijit / DojoX family is the amazing GFX library.  GFX lives within the dojox.gfx namespace and provides the foundation of Dojo's charting, drawing, and sketch libraries.  GFX allows you to create vector graphics (SVG, VML...

  • By
    Basic AJAX Requests Using MooTools 1.2

    AJAX has become a huge part of the modern web and that wont change in the foreseeable future. MooTools has made AJAX so simple that a rookie developer can get their dynamic pages working in no time. Step 1: The XHTML Here we define two links...

Discussion

  1. Thanks, I use a lot (probably unnecessary) if/else statements which could be cut down.

  2. Nice article! that’s something I wanted to learn/practice to save some time and clear my code when I have to use simple if/else, I’ll try to add this to my coding habits ;)

  3. The example with intermediate variables is interresting, but i’d better use a switch structure instead. What do you think?

    But thanks for the coding tips :)

  4. A switch could work there too Dagnan. Good point!

  5. TedInAK

    Nice write up! I used to use the parentheses the same as in your example:

    $dynamic = ($language == 'php' ? true : false);

    But was “mildly scolded” by a JS guru much smarter than I. He said it should be:

    $dynamic = ($language == 'php') ? true : false;

    Now technically, either way is “correct” since JS allows both ways. But I found myself agreeing with said guru, mainly that the logic test portion should be in the parentheses. Example:

    if ($language == 'php') {
      // code
    } else {
      // code
    }
    

    So to his way of thinking (and now mine), since in this structure it’s just the logical test that is within the parentheses, so should it be in the ternary structure.

  6. monster87

    Nice write up! I used to use the
    parentheses the same as in your
    example:

    $dynamic = ($language == ‘php’ ? true
    : false);

    But was “mildly scolded” by a JS guru
    much smarter than I. He said it should
    be:

    $dynamic = ($language == ‘php’) ? true
    : false;

    Now technically, either way is
    “correct” since JS allows both ways.
    But I found myself agreeing with said
    guru, mainly that the logic test
    portion should be in the parentheses.
    Example:

    if ($language == ‘php’) { // code }
    else { // code }

    Even simpler would be:

    $dynamic = $language == 'php' ? true : false;
    

    or even:

    $dynamic = $language == 'php';
    

    in JS this works the same way.

    And for anyone who is interested.
    Although it seems to miss in php, javascript does have an interesting even shorter expression for when working with if it’s false then use this default

    $somevar = $othervar ? $othervar : "default";
    
    $somevar = $othervar || "default";
    

    (in php $somevar will evaluate to ‘true’ since a filled string (“default”) is always ‘true’ in a or(||)-situation)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!