1

corresponding nested ternary operator in php? and In which order are nested short hand assignments evaluated? explain that ternary operators in PHP don't evaluate as expected.

See this example:

echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ? 0 : 1 ? 1 : 2 ? 2 : 3; //2

Even reading the docs I still fail to understand why short and long form are evaluated differently?

Community
  • 1
  • 1
andig
  • 13,378
  • 13
  • 61
  • 98
  • What do you don't understand? You already have a question with the correct dupe, which explains that the ternary is left associative – Rizier123 Aug 27 '15 at 11:33
  • @Rizier123 but if both examples are left-associative, why do they output different values? does using short-hand group internally or have a different order of precedence? – billyonecan Aug 27 '15 at 11:52
  • @billyonecan Because they are different ternary operators your 2 lines are different – Rizier123 Aug 27 '15 at 11:55
  • @billyonecan Wrote and answer: http://stackoverflow.com/a/32248940/3933332 And hopefully the step by step with the formatting helps to show what is going on – Rizier123 Aug 27 '15 at 12:18
  • @Rizier123 it's not my question, I was just curious :) – billyonecan Aug 27 '15 at 12:20
  • @billyonecan sorry my bad. Totally though you were OP which wrote the comment. – Rizier123 Aug 27 '15 at 12:22

1 Answers1

3

You already start with a wrong assumption that these 2 code lines are identical, because they are not. The ternary (expression ? IF TRUE : IF FALSE) operator is left associative.

So if you go through step by step you maybe see it better:

First ternary line:

echo 0 ?: 1 ?: 2 ?: 3; //1

With parentheses:

echo ((0 ?: 1) ?: 2) ?: 3; //1
      └──────┘                  //0 → FALSE 
       ↓                        //Second expression: 1  
echo ((1) ?: 2) ?: 3; //1
     └────────┘                 //1 → TRUE
      ↓                         //First expression: 1  
echo (1) ?: 3; //1
     └──────┘                   //1 → TRUE
     ↓                          //First expression: 1 
echo 1; //1

Second ternary line:

echo 0 ? 0 : 1 ? 1 : 2 ? 2 : 3; //2

With parentheses:

echo ((0 ? 0 : 1) ? 1 : 2) ? 2 : 3; //2
      └─────────┘                       //0 → FALSE 
       ↓                                //Second expression: 1
echo ((1) ? 1 : 2) ? 2 : 3; //2
     └───────────┘                      //1 → TRUE 
      ↓                                 //First expression: 1
echo (1) ? 2 : 3; //2
     └─────────┘                        //1 → TRUE 
     ↓                                  //First expression: 2
echo 2; //2
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • 1
    Ahhhh, finally it clicked with me what "left associative" actually means. Much appreciated, thanks! – andig Aug 27 '15 at 12:38