Why is the output of `echo true? 'true? 'b': 'c'; `` b '?

I have this bit of PHP code:

echo true ? 'a' : true ? 'b' : 'c'; 

The result of this:

b

But the expected result:

a

+4
source share
2 answers

Since your code is evaluated as follows:

 echo (true ? 'a' : true) ? 'b' : 'c'; 

this is equivalent to:

 echo (true) ? 'b' : 'c'; 

Then the result is 'b'

+2
source

ternary operator in php left associative.

You need to use

 echo true ? 'a' : (true ? 'b' : 'c'); 
+11
source

All Articles