java, ruby, python, php, religion, theism, atheism, ignosticism, portfolio, canada, programming, ruby sucks, python sucks, java rocks

PHP quirk with inline "if"

Posted January 22, 2010

Today, I discovered an interest quirk in PHP 5. I needed to set a single value based on various possible string values. For whatever reason, I decided a big set of "if/elseif" statements wouldn't do, and a switch would be overkill for simply setting a single value. What I tried to do was use in inline if this:

 

$maxLength = $name == 'apiUser'
        ? 20
        : $name == 'apiKey'
                ? 50
                : $name == 'userName'
                        ? 20
                        : 255;

Much to my dismay (and befuddlement), the answer was always the value for 'userName'. I had done this many time before in C/C++ and in Java, so I knew logically it was possible, but what could be the issue here? Well, it seems PHP has a slightly different way of processing these - simply adding in brackets solved the problem:

$maxLength = ($name == 'apiUser'
        ? 20
        : ($name == 'apiKey'
                ? 50
                : ($name == 'userName'
                        ? 20
                        : 255)));

And presto, it works as expected.

Comments

There are no comments for this post.

Add comment

Visit my Friends and Family

If you've enjoyed my site, please take a moment to visit my friends and family, many of whom have some interesting insights, and entertaining thoughts and ideas.

Widgets

Advertising


Windows 7 Sins
 

ss_blog_claim=07d81221ccea23e9eae5fdaf510cea20