PHP nested conditional operator bug?
Asked Answered
W

4

4
   
                return
                    true  ? 'a' :
                    false ? 'b' :
                                                           'c';

This should return 'a', but it doesn't. It returns 'b' instead. Is there a bug in PHP's order of handling the different parts of the conditional operators?

I got the idea from Are multiple conditional operators in this situation a good idea? where it does seem to work correctly.

(the true and false are for the purpose of the example, of course. in the real code they are statements that evaluate to true and false respectively. yes, i know that for sure)

Wring answered 17/12, 2009 at 12:27 Comment(2)
i recommend phpa for playing with issues like this. it's a python-like interpreter shell for php. find it here: david.acz.org/phpaAnaemic
While I like the ternary operator, this is one great example of how it can completely clutter up readability.Narra
V
8

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

From the PHP Manual under "Non-obvious Ternary Behaviour".

Ternary operators are evaluated left to right, so unless you add it the braces it doesn't behave as you expect. The following would work though,

return (true ? "a" : (false ? "b" : "c"));
Vaivode answered 17/12, 2009 at 12:35 Comment(0)
L
6

Suspect it's evaluating (true ? 'a' : false) as the input to the second ternary operator and interpreting 'a' as true. Try bracketing appropriately.

Leyba answered 17/12, 2009 at 12:30 Comment(0)
A
3

order of operations:

>>> return true ? 'a' : false ? 'b': 'c';
'b'
>>> return true ? 'a' : (false ? 'b': 'c');
'a'
Anaemic answered 17/12, 2009 at 12:29 Comment(0)
C
0

Let me explain in same way it was explained to me. But you have to pay attention in parenthesis to understand what is happening.

The PHP

The PHP code below

true ? "a" : false ? "b" : "c"

Is equivalent to:

(true ? "a" : false) ? "b" : "c"

Another languages

The code below

true ? "a" : false ? "b" : "c"

Is equivalent to:

true ? "a" : (false ? "b" : "c")
Charmian answered 21/12, 2016 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.