So, I just read this blog post , and I was confused by the "triple operator - left-associative" part, so I ran an example code - in the interpreter:
$arg = 'T'; $vehicle = ( ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' ) ? 'airplane' : ( $arg == 'T' ) ? 'train' : ( $arg == 'C' ) ? 'car' : ( $arg == 'H' ) ? 'horse' : 'feet' ); echo $vehicle;
and indeed, he returns horse , which is the counter-intuitiveness that was the point in the blog post.
Out of curiosity, I then tried to "make this work", rewriting it in accordance with what I thought the "left-associative" would like. I got this (formatting is weird, but it makes it clearer, at least in my head):
$arg = 'T'; $vehicle = ( ( $arg != 'B' ) ? ( $arg != 'A' ) ? ( $arg != 'T' ) ? ( $arg != 'C' ) ? ( $arg != 'H' ) ? 'feet' : 'horse' : 'car' : 'train' : 'airplane' : 'bus' ); echo $vehicle;
Now it works as expected, in the sense that sometime the $arg symbol returns a vehicle that starts with that symbol (lowercase, but that doesn't matter here).
Curious, because I donβt understand why, since the former does not work, I wondered if the latter would end in a right-associative language, because it does not look like this. Therefore, I tested it in a java interpreter. The code is here for those who want to try and save a few seconds.
class Main { public static void main(String[] args) { Character arg = 'a'; String vehicle = ( ( arg == 'B' ) ? "bus" : ( arg == 'A' ) ? "airplane" : ( arg == 'T' ) ? "train" : ( arg == 'C' ) ? "car" : ( arg == 'H' ) ? "horse" : "feet" ); System.out.println(vehicle); vehicle = ( ( arg != 'B' ) ? ( arg != 'A' ) ? ( arg != 'T' ) ? ( arg != 'C' ) ? ( arg != 'H' ) ? "feet" : "horse" : "car" : "train" : "airplane" : "bus" ); System.out.println(vehicle); } }
Both formats work in java. So what gives in php? I heard that he essentially evaluates leading equalities as final ( $arg == 'H' ). But if this is so, it means that he acted as if it were
$vehicle = ((($arg == 'B') || ($arg == 'A') || ($arg == 'T') || ($arg == 'C') || ($arg == 'H')) ? 'horse' : 'feet');
That doesn't make sense to me. In the second php example that I gave, I only moved to where the equalities go, embedded in the if true part of the triple expression instead of the if false part. I do not understand why the first method did not work if the second does. It seems more like a mistake than βhow it should work,β and I'm just misinterpreting the things that I should be.
NOTE. I know that I can simply copy parentheses around things to make the expression evaluate as I want (which seems to be right-associative). I am not looking for βhow to make this work,β I want to know why this is not so.