Tim-Hinnerk Heuer
2013-10-18 00:46:04 UTC
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
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
the ternary operator?
Tim-Hinnerk Heuer
Twitter: @geekdenz
Blog: http://www.thheuer.com
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-leftas 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 ofthe ternary operator?
Tim-Hinnerk Heuer
Twitter: @geekdenz
Blog: http://www.thheuer.com