Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP nested conditional operator bug?

   
                return
                    true  ? 'a' :
                    false ? 'b' :
                                                           'c';

This should return 'a', but it doesn't. It returns 'b' instead. Is there a bug in PHP's order of handling the different parts of the conditional operators?

I got the idea from Are multiple conditional operators in this situation a good idea? where it does seem to work correctly.

(the true and false are for the purpose of the example, of course. in the real code they are statements that evaluate to true and false respectively. yes, i know that for sure)

like image 429
Bart van Heukelom Avatar asked Dec 03 '22 13:12

Bart van Heukelom


2 Answers

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious

From the PHP Manual under "Non-obvious Ternary Behaviour".

Ternary operators are evaluated left to right, so unless you add it the braces it doesn't behave as you expect. The following would work though,

return (true ? "a" : (false ? "b" : "c"));
like image 156
Rich Adams Avatar answered Dec 15 '22 09:12

Rich Adams


Suspect it's evaluating (true ? 'a' : false) as the input to the second ternary operator and interpreting 'a' as true. Try bracketing appropriately.

like image 42
David M Avatar answered Dec 15 '22 10:12

David M