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.

10 Comments

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.

Smartmatch however…

… “will take two major versions to fix”, is that the missing part of your sentence, Joel? :-)


<?php
    if (0 == "zero") {
        print "welp\n";
    }
?>

welp


<?php
    $a = array( 'a' => 1, 'b' => 2);
    $b = array( 'b' => 1, 'a' => 2);

    print '$a < $b: ' . ($a < $b ? 'true' : 'false') . "\n";
    print '$a > $b: ' . ($a > $b ? 'true' : 'false') . "\n";
?>

$a is simultaneously greater than and less than $b.

#!perl
if (0 == "zero") {
  print "welp\n";
}

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 wanted 0 === "zero".

About Ovid

user-pic Freelance Perl/Testing/Agile consultant and trainer. See http://www.allaroundtheworld.fr/ for our services. If you have a problem with Perl, we will solve it for you. And don't forget to buy my book! http://www.amazon.com/Beginning-Perl-Curtis-Poe/dp/1118013840/