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.


