3

Please consider the follwing code construction:

condition  ? code_if_true  : 
condition2 ? code_if_true2 : 
             code_if_false;

This doesn't work for PHP whereas it does for JavaScript.

Is there a way to get this working for PHP?

Arjan
  • 22,808
  • 11
  • 61
  • 71
Durian Nangka
  • 257
  • 4
  • 17
  • how is it not working? what is the error? – tomexsans Jan 27 '13 at 10:54
  • 3
    It does work in PHP. What is the specific problem you are having? – Salman A Jan 27 '13 at 10:54
  • 2
    You need to be a bit more specific than "It doesn't work". And using this shorthand with anything that depends on complex logic is only going to make your code unreadable anyway. You're much better off using nested if statements. – GordonM Jan 27 '13 at 10:57
  • 3
    It does work in PHP, but [not the same way](http://us.php.net/ternary#example-121) as it does in JS. – DCoder Jan 27 '13 at 10:57

1 Answers1

9

In PHP, the conditional operator is left-associative[PHP.net], compared to virtually all other languages where it is right-associative.

That's why you need to use parentheses to control the order of evaluation1:

 condition  ? code_if_true  : 
(condition2 ? code_if_true2 : 
              code_if_false ); 

1The order in which which operators are resolved, not when operands are evaluated. The latter is basically undefined[PHP.net]

phant0m
  • 16,595
  • 5
  • 50
  • 82