Which coding style you use for ternary operator?

Imran picture Imran · Oct 28, 2008 · Viewed 42.2k times · Source

I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example:

$value = ( $a == $b ) 
            ? 'true value # 1'
            : ( $a == $c )
                ? 'true value # 2'
                : 'false value';

Personally which style you use, or find most readable?

Edit: (on when to use ternary-operator)

I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.

Answer

Simon Howard picture Simon Howard · Oct 28, 2008

The ternary operator is generally to be avoided, but this form can be quite readable:

  result = (foo == bar)  ? result1 :
           (foo == baz)  ? result2 :
           (foo == qux)  ? result3 :
           (foo == quux) ? result4 : 
                           fail_result;

This way, the condition and the result are kept together on the same line, and it's fairly easy to skim down and understand what's going on.