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.


Matthew Kerwin

Published
Modified
License
CC BY-SA 4.0
Tags
gotcha, php, software

Comments powered by Disqus