PHP And Nesting Ternary Operators
Posted
- January 9th, 2008
Comments
Tags
I came across an interesting quirk in PHP today. The way a nested ternary operator is evaluated in PHP is unlike that of any other language I’ve come across: left to right.
Ex:
<?php
$test = 'one';
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';
?>
What do you suppose that prints? Wrong, the answer is ‘two’. Let’s break this down in how it is working, shall we.
<?php
$test = 'one';
echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three';
?>
Here, I’ve emphasized the first ternary operation. What PHP will do is evaluate this section and return a value, in this case it is the string ‘one’. The boolean value of the string ‘one’ is true. So, for the second ternary operation, ‘two’ gets selected.
No other language I know of acts like this.
Hopes this help someone one day.
February 14th, 2008 at 7:32 am |
You helped me today, thanks!
February 25th, 2008 at 3:36 pm |
putting parentheses around the inner ternary operator will make it evaluate properly, it is definitely annoying when you first come across it.
July 20th, 2009 at 10:55 am |
Oh man i spent an two hours on tracking down a “bug” from this. I’m glad now i know why PHP is acting like it is
September 24th, 2010 at 3:11 pm |
Trying to learn more about web programing.