4

I have this bit of PHP code:

echo true ? 'a' : true ? 'b' : 'c';

The output of this is:

b

But the output I expected was:

a

Leigh
  • 12,859
  • 3
  • 39
  • 60
mrsrinivas
  • 34,112
  • 13
  • 125
  • 125
  • 3
    __Don't__ nest ternary operators.... it makes your code unreadable, and is well documented as a bad practise because the logic doesn't execute as you'd expect – Mark Baker Feb 07 '13 at 12:34
  • 2
    echo (true ? 'a' : (true ? 'b' : 'c')); –  Feb 07 '13 at 12:34
  • http://www.php.net/manual/en/language.operators.comparison.php#example-121 – deceze Feb 07 '13 at 12:35
  • 1
    @MarkBaker: That's only because the condtional operator in php is right associative. Other languages are sane and the output is as expected. – Femaref Feb 07 '13 at 12:35
  • 1
    @Femaref - It's still documented behaviour, and still a lot harder to read than nested ifs – Mark Baker Feb 07 '13 at 12:37
  • 1
    @MarkBaker that's highly subjective. Personally I think the ternary ?: is easier to read than nested ifs if the conditions and the results are short. – Magnus Feb 07 '13 at 12:38
  • A simple ternary is easier to read.... nested ternaries aren't, and are still subject to a lot of confusion over their behaviour (ergo this question among many).... and if I ever see nested ternaries used in code I'm reviewing for recruitment, then that person would never get a job in my company – Mark Baker Feb 07 '13 at 12:41

2 Answers2

11

the ternary operator in php is left-associative.

You need to use

echo true ? 'a' : (true ? 'b' : 'c');
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Femaref
  • 60,705
  • 7
  • 138
  • 176
2

Because your code evaluates like this:

echo (true ? 'a' : true) ? 'b' : 'c';

it equivalent to:

echo (true) ? 'b' : 'c';

Then the result is 'b'