4
$chow = 3;
echo ($chow == 1) ? "one" : ($chow == 2) ? "two" : "three";

output: three

$chow = 1;
echo ($chow == 1) ? "one" : ($chow == 2) ? "two" : "three";

output: two

Can anyone explain why the output is "two" when $chow = 1 instead of "one"?

Kamil Karkus
  • 1,283
  • 1
  • 11
  • 29
Monir
  • 115
  • 1
  • 7

3 Answers3

12

This is because the ternary operator (?:) is left associative so this is how it's getting evaluated:

((1 == 1) ? "one" : (1 == 2)) ? "two" : "three"

So 1 == 1 -> TRUE means that then it's:

"one" ? "two" : "three"

And "one" -> TRUE so the output will be:

two
Salman A
  • 262,204
  • 82
  • 430
  • 521
Rizier123
  • 58,877
  • 16
  • 101
  • 156
6
$chow = 1;
echo ($chow == 1) ? "one" : (($chow == 2) ? "two" : "three");

remember to use brackets when result of operation can be unclear

now output is one

Kamil Karkus
  • 1,283
  • 1
  • 11
  • 29
  • 1
    *Can anyone explain why the output is "two"* This "answer" doesn't answer the question, because it's asking for an explanation not for a solution how to get "one" as output – Rizier123 Feb 25 '15 at 10:10
  • it's obvious that tenary operator will be evaluated from right to left – Kamil Karkus Feb 25 '15 at 10:20
  • 1
    So obvious that you are even wrong! it's from left to right! left associative means from left -> right! – Rizier123 Feb 25 '15 at 10:21
0

The operator is confused, you need to put brackets around your second codition. use the code below

$chow = 1;
echo ($chow == 1) ? "one" : (($chow == 2) ? "two" : "three"); //returns 1

Hope this helps you

Utkarsh Dixit
  • 4,267
  • 3
  • 15
  • 38