Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was asked to perform this operation of ternary operator use:

$test='one';

echo $test == 'one' ? 'one' :  $test == 'two' ? 'two' : 'three';

Which prints two (checked using php).

I am still not sure about the logic for this. Please, can anybody tell me the logic for this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
610 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well, the ? and : have equal precedence, so PHP will parse left to right evaluating each bit in turn:

echo ($test == 'one' ? 'one' :  $test == 'two') ? 'two' : 'three';

First $test == 'one' returns true, so the first parens have value 'one'. Now the second ternary is evaluated like this:

'one' /*returned by first ternary*/ ? 'two' : 'three'

'one' is true (a non-empty string), so 'two' is the final result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...