I understand the concept of associativity with regards to mathmatical and assignment operators, but this is going right over my head (and making a whistling noise as it passes).
I understand what is happening (the outcome); I don't understand how it is happening (the process):
I'm pretty sure I've run into this before, too - but I didn't know what was going on. Good to know I am not the crazy one (at least, not for this reason )
I always use parentheses when I combine ternary expressions like that, so when I come back to them later I don't have to remember how they work again.
Well, actually, I no longer use ternary expressions except for very simple cases, as I'm more into readability now than I am into terseness.
Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett
"But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because he’s a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html
I try to use it only for if/else variable assignments.
Since discovering this issue, I've resolved to use them only in simple cases (no more "nested" ternaries).
Invert the conditions (i.e., !condition) and switch the order of their (if true) / (if false) expressions. You'll end up indenting out, then indenting back in, like this:
PHP Code:
echo ( !TRUE ?
!FALSE ?
"b":
"c":
"a"
);
echo ( !TRUE ?
!TRUE ?
"b":
"c":
"a"
);
equivalent conditions, but it works as expected.
Now, I'm not advocating using deeply nested ternaries everywhere. It's just a thorn in my paw when I can't get something to work that should work, dammit. So, just remember to always put new conditionals first, in the "if true" expression, and never in the "if false".
yeah. both options are kinda kludgy, unfortunately. I don't think it's reasonable/practical to have to put conditions in a specific (unexplained!) order, or manually nest everything in parenthesis, to make it work.
(I'm not advocating deeply-nested conditionals everywhere either, but the above is completely lucid compared to something like c1 ? c2 : c3 ? c4 ? c5 ? v3 : v4 : (c6 ? v5 : v6) : (c7 ? v7 : v4).)
One thing I'll observe at this point - because I see a lot of code where the author has apparently gone to a lot of trouble to avoid it - is that if(condition ? test1 : test2) is legal and doesn't need to be written as if((condition && test1) || (!condition && test2)).
Last edited by Weedpacket; 12-25-2012 at 08:22 PM.
Bookmarks