Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

a style I sometimes use, which I'm bringing up since it hasn't been mentioned, is like this:

$result = ($x == y)
        ? "foo"
        : "bar";

..but usually only if putting it all on one line makes it too long. I find that having the = ? : all line up makes it look neater.

PHP nested ternary operators behave differently.

This syntax passes all the following tests. Based on http://deadlytechnology.com/web-development-tips/php-ternary-syntax/

$myvar = ($x == $y)
?(($x == $z)?'both':'foo')
:(($x == $z)?'bar':'none');

.

See: http://au.php.net/ternary

Example #3 "Non-obvious Ternary Behaviour" explains why the following does not work in PHP.

$x = 1;
$y = 2;
$z = 3;   
$myvar = ($x == $y) 
       ? "foo" 
       : ($x == $z) 
         ? "bar" 
         : "none";  
$myvar == 'none'; // Good

$x = 1;
$y = 2;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Good

$x = 1;
$y = 1;
$z = 3;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!

$x = 1;
$y = 1;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!

ternary operators are short effective ways to write simple if statements. They shouldn't be nested or difficult to read. Remember: You write the software once but is is read 100 times. It should be easier to read than write.

I tend to enclose the condition in parentheses : (a == b) ? 1 : 0

I'll dissent with the common opinion. I'm sort of like Imran with my conditional operator style. If it fits cleanly on one line, I keep it on one line. If it doesn't fit cleanly on one line, I do break it, but I use only a single tab (4 spaces; I have VS set to insert spaces for tabs) for the indent. I don't immediately jump to if-else, because a lot of the time the conditional operator makes more sense contextually. (If it doesn't make sense contextually, however, I simply don't use it.)

Also, I don't nest conditional operators. At that point, I do find it too difficult to read, and it's time to go to the more verbose if-else style.

The "contrived example" is how I would indent it, except that I would indent from the left margin, not based on where the ( or whatever is on the line above.

To the ternary detractors - readability is the point. If you don't think it makes for more readable code, don't use it. But I find the contrary to be the case at least some of the time.

The ternary conditional can make code cleaner and more elegant, and most importantly, help you put emphasis on the right things and avoid repeating yourself. Consider using them, but do not make the code less readable by doing so. In VB.NET:

'before refactoring 
If x = 0 Then                    ' If-Then-Else puts emphasis on flow control
    label = "None"
Else
    label = Foo.getLabel(x)      '  If-Then-Else forces repeat of assignment line
End If

'after refactoring    
label = If(x = 0, "None", Foo.getLabel(x)) ' ternary If puts emphasis on assignment

Note that "it is less readable" is not the same thing as "I'm not used to seeing that".

I don't use it. It always smelled to me like trying to save space and typing in source code with the expectation that small source == more efficient compiled code.

I don't find it readable at all, but much of that is because I just never use it.

I tend not to use the ternary operator at all as I find if .. else much more readable.

Imran, you have formatted this beautifully. However, the ternary operator does tend to get unreadable as you nest more than two. an if-else block may give you an extra level of comprehensible nesting. Beyond that, use a function or table-driven programming.

$foo = (isset($bar)) ? $bar : 'default';

I personally only use it for an assignment of a variable (in java) for example :

String var = (obj == null) ? "not set" : obj.toString();

and (other example) when using function that doesn't allow null parameter such as :

String val; [...]
int var = (val == null) ? 0 : Integer.parseInt(val);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top