Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if/else shorthand notation - multiple conditions

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?

like image 301
Durian Nangka Avatar asked Dec 20 '25 01:12

Durian Nangka


1 Answers

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]

like image 52
phant0m Avatar answered Dec 21 '25 14:12

phant0m