سؤال

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