Which coding style you use for ternary operator? [closed]
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.
Solution 1:
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.
Solution 2:
I try not to use a ternary operator to write nested conditions. It defies readability and provides no extra value over using a conditional.
Only if it can fit on a single line, and it's crystal-clear what it means, I use it:
$value = ($a < 0) ? 'minus' : 'plus';