2

Possible Duplicate:
PHP ternary operator not working as expected

I dont know what is wrong with my code? My PHP Version is 5.4.7.

$b = 'a';
$c = 'd';
echo $b == 'a' ? 2: $c == 'a' ? 1 : 0; 

output 1

right answer should be 2.....

Thank you very much for your advice.

Community
  • 1
  • 1
Micah
  • 4,254
  • 8
  • 30
  • 38
  • 7
    The **language manual** clearly states: [It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:](http://us.php.net/ternary#example-121). – DCoder Jan 18 '13 at 13:16

1 Answers1

8

You need to add some parenthesis.

$b = 'a';
$c = 'd';
echo ($b == 'a') ? 2 : ($c == 'a' ? 1 : 0);
Vlad Preda
  • 9,780
  • 7
  • 36
  • 63