문제

In php if you

echo (('a'=='a')?'A':('a'=='b')?'B':'C');

The result will be:

B

Which is total rubbish. According to the php docs (example#3) this is because

ternary expressions are evaluated from left to right.

which doesn't really explain it for me: evaluating from left to right, ('a'=='a') so the result is 'A', no!? Really at a loss to understand how php can get 'B' from this. This sort of statement will work in many, many languages, but not php. Does anyone understand the php logic here, and how best to fix this in php?

도움이 되었습니까?

해결책

The entire expression on the left is evaluated. These are the same:

echo( ('a' == 'a') ? 'A' : ('a' == 'b')  ? 'B' : 'C');
echo((('a' == 'a') ? 'A' : ('a' == 'b')) ? 'B' : 'C');

The expression below evaluates to A:

('a' == 'a') ? 'A' : ('a'=='b');

And this express evaluates to B:

('A' ? 'B' : 'C');

If you move the parentheses, the expression will evaluate as you're expecting:

echo(('a' == 'a') ? 'A' : (('a' == 'b') ? 'B' : 'C'));

다른 팁

Experimentally,

echo (('a'=='a')?'A':(('a'=='b')?'B':'C'))

Outputs

A

It looks like the php implementation has mucked up operator precedence, giving : a higher precedence than ?, so without the brackets,

('a'=='a')?'A':('a'=='b')

is grouped together, so the expression:

('a'=='a')?'A':('a'=='b')?'B':'C'

evaluates to

('A'?'B':'C');

Which results in 'B' (as 'A' is not 0 or FALSE, and so is TRUE).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top