PHP quirk with inline "if"
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.
- Crause Family - the family website
- Peter Crause - my father
- Justin Crause - my brother
- Cencina Photomagic - great photographer
- Shawn Adrian - talented graphic designer, bad driver, and all-round fun guy