On 10/17/2013 8:50 PM, Tim-Hinnerk Heuer wrote:
http://php.net/manual/en/language.operators.comparison.php#example-122
Found this in relation, so this behaviour is documented.
Tim-Hinnerk Heuer
Twitter: @geekdenz
Blog: http://www.thheuer.com
On 18 October 2013 13:46, Tim-Hinnerk Heuer <th.heuer@xxxxxxxxx> wrote:
Hi,
I've been a PHP programmer for several years now and have a bit of a
love-hate relationship with it. It's great for doing something quickly,
especially web stuff, but recently I have heard people moaning about PHP a
lot and did some research and found this:
http://webonastick.com/php.html
One thing I had to get my head around is this:
The ternary operator
<?php
$foo = 1;
print(($foo == 1) ? "uno" : ($foo === 2) ? "dos" : "tres");
print("\n");
outputs
dos
because the operator is left-to-right associative instead of right-to-left
as in other languages. I was thinking there must be a reason for this.
Speed? Is it faster to evaluate/implement all operators as left-to-right?
I noticed that the above could easily be fixed by saying:
<?php
$foo = 1;
print(($foo == 1) ? "uno" : (($foo === 2) ? "dos" : "tres"));
print("\n");
outputs
uno
Was this a deliberate design decision or is it a flaky implementation of
the ternary operator?
Tim-Hinnerk Heuer
Twitter: @geekdenz
Blog: http://www.thheuer.com
Having endured this entire thread (from T-to-B) I have to add my $.02.
I recently experienced the rather unexpected outcome of a ternary within
a ternary. Rather than consider the order of evaluation being L-to-R or
R-to-L, I merely diagnosed it as a simple bug in PHP - which BTW I love,
despite it's less than consistent syntax. Reading all the talk of order
of evaluation, I have to say in my 40+ years of programming in a variety
of languages, I can't recall ever having to consider the topic. When I
wrote code I always expected and relied upon the order being the way I
wrote it. And - I usually added parentheses to help clarify in my mind
what I was doing with the statement as I wrote it, although sometimes I
knew they were necessary to achieve the analysis I had in mind.
So - as expected, the ternary operator does work from L-to-R except when
joined with a second (or third?) ternary operator. Why that is I can't
figure out other than to assume it's an un-resolved bug, that occurs so
seldom it's probably never been issued. Oh, well.....
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php