Possible Duplicate:
Problem with PHP ternary operator
I was reading up a bit on PHP in this article, and I stopped for a while to consider one of his gripes. I can't figure out how on earth PHP comes to the result that it does.
Unlike (literally!) every other language with a similar operator, ?: is left associative. So this:
$arg = 'T'; $vehicle = ( ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' ) ? 'airplane' : ( $arg == 'T' ) ? 'train' : ( $arg == 'C' ) ? 'car' : ( $arg == 'H' ) ? 'horse' : 'feet' ); echo $vehicle;
prints horse.
What logical path does PHP follow that results in 'horse'
being assigned to $vehicle
?
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Bracketing is the solution for both understanding and fixing:
This should have the unintended result (
horse
):This should have the indended result (
train
):