Reduce code with the ternary operator

November 10, 2008 / Filed under:

When writing applications, it's important to find ways to reduce code. More code equals more development, more maintenance, and more headaches.

One quick way to help reduce code is to use "ternary" (also often called "tertiary") syntax for simple if/else statements. This syntax is supported in PHP, JavaScript, Ruby, and many other languages.

Consider this PHP example:

if ($var == true) {
    $go = 1;
}
else {
    $go = 0;
}

This is an extremely basic if/else test, which comprises six lines. Not such a big deal for a single test, but imagine you had to do this for a dozen different variables. For something so simple, we should be able to do it all in a single line. Using "ternary" syntax, we can:

$go = ($var == true) ? 1 : 0;

As you can see, we start out by setting the $go variable immediately. It's almost like we're reversing the process. The $go variable now equals the result of the if/else test, whereas before, we ran the test first, then set the variable.

The if/else test is also much simpler. We use parenthesis to hold the expression, just like before. But gone now are the brackets. Instead, we use ? to indicate a true result of the expression, and a : to indicate a false result. Don't forget to include the semi-colon, and you're done.

One thing to be aware of is you must include an "else" result (the portion after the colon). Sometimes your if tests may not need an else, but with ternary syntax, you have to put something there.

For example, this would not work:

$go = ($var == true) ? 1;

Hope this quick tip helps save you some lines of code.

Comments/Mentions