I’m having trouble understanding why my PHP code returns "three" instead of "two". Here’s the code:
php
<?php $a = 2; echo $a == 1 ? "one" : $a == 2 ? "two" : $a == 3 ? "three" : "others"; ?>
When I run this in PHP versions earlier than 5.3, the output is "three". Can someone explain why this happens and how the code works?
2
Answers
Your code is quite unreadable, it hurts my brain. Make it readable and you probably also solve any problems you have.
How about this:
This code is readable and, may I say, slightly more performant.
There are also many other ways of doing it. Anything is better than multiple ternary operators on one line.
The ternary in PHP works in other direction compared to other programming languages.
is the same as
This can be reduced to
CONDITION ? "three" : "others"
where CONDITION is(( $a == 1 ? "one" : $a == 2 ) ? "two" : $a == 3 )
. And CONDITION is always true.Compared to other programing languages, I think you want