YoongKang Lim
YoongKang Lim

Reputation: 566

PHP precedence operator A? 'True': 'False'

I facing a problem where i put more condition into this statement A? 'True': 'False'

As what i know the Associativity of ?: is from the left

This is the example

(1 == 2)?'a':(2==3)?'b':'c' = answer 'c'
(1 == 2)?'a':(2==2)?'b':'c' = answer 'b'

As what i know (1 == 2)==false , then it went to false condition (2==3) and false return so the answer is c (might be wrong, please correct me)

Above example work fine, but it start to went wrong when

(1 == 1)?'a':(2==3)?'b':'c' = answer 'b'
(1 == 1)?'a':(2==2)?'b':'c' = answer 'b'

As what i know (1 == 1) == true, so it should pick the 'a' and ignore the rest.

Reference: http://php.net/manual/en/language.operators.precedence.php

Upvotes: 1

Views: 85

Answers (2)

Audite Marlow
Audite Marlow

Reputation: 1054

In your statement (1 == 1) ? 'a' : (2 == 3) ? 'b' : 'c', the first condition statement does return 'a', but since there's another condition statement right after your first, it wants to compare 'a' for true or false. Since a string in a condition statement will always return true, the second condition statement returns 'b'.

You're going to want to use your statement as follows:

(1 == 1) ? 'a' : ((2 == 3) ? 'b' : 'c')

Upvotes: 2

Jay Blanchard
Jay Blanchard

Reputation: 34426

Nested ternaries can be problematic in as much as it is hard to read what is going on. Bracketing properly cures the issue:

(1 === 1) ? 'a' : ((2==3) ? 'b' : 'c')

This reads like this: if 1 equals 1 then a, else perform if 2 equals 3.

Upvotes: 6

Related Questions