What does this PHP print?
Via this blog entry which I'm sure some of you have seen before, the following PHP prints "horse".
<?php
$arg = 'T';
$vehicle = ( ( $arg == 'B' ) ? 'bus' :
( $arg == 'A' ) ? 'airplane' :
( $arg == 'T' ) ? 'train' :
( $arg == 'C' ) ? 'car' :
( $arg == 'H' ) ? 'horse' :
'feet' );
echo $vehicle;
?>
No fun shooting fish (or a horse) in a barrel, but wow. Just wow.
Wow! Icky ick. It took me a long time to figure out what the heck was going on. Now that I get it, you can get 'feet' by changing 'car' to ''. Yeah that's logical.
But why such result? Could anyone explain?
I'm surprised I had so much trouble making that code do the expected thing, so I had to explain it all.
To be fair, the PHP manual acknowledges this problem and tells people not to nest them. It's not like Perl has a similar problem with a certain 5.10 feature.
That would be a fair point if umpteen other languages hadn’t already gotten the ternary operator right. To my knowledge, the same cannot be said of the smart match operator.
Luckily for PHP, if they ever want to correct their mistake, they need only do so, and then indicate the breaking change by increasing their major version number. Smartmatch however...
Also PHP has had a "switch" statement since forever. Whatsmore, the optional braces make an if/elseif/.../else chain in PHP much more appealing than it is in Perl.
… “will take two major versions to fix”, is that the missing part of your sentence, Joel? :-)
welp
$a is simultaneously greater than and less than $b.
In both the PHP and Perl versions, it's down to a poor choice of operator. In Perl you probably meant
0 eq "zero"
; in PHP you probably wanted0 === "zero"
.