PHP Ternary Precedence

Take this statement:

true ? 1 : false ? 2 : 3

In ruby, C, Java, etc. it evaluates to 1.
In PHP it evaluates to 2.

Apparently PHP evaluates inside-out:

(true ? 1 : false) ? 2 : 3
=> (1) ? 2 : 3
=> 2

...where everything else evaluates left-to-right:

true ? 1 : (false ? 2 : 3)
=> 1

Interesting.



thumbnail image

Matthew Kerwin

Published
Modified
License
CC BY-SA 4.0
Tags
gotcha, php, software
Take the statement: "true ? 1 : false ? 2 : 3". In PHP it probably doesn't do what you think it does.

Comments powered by Disqus