Which coding style you use for ternary operator? [closed] Which coding style you use for ternary operator? [closed] php php

Which coding style you use for ternary operator? [closed]


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.


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';


Personally, I only use the ternary operator if it fits on one line. If it need to span, then it's time for the good old

if else if else