In any normal language, the ternary operator is right-associative, so you expect your code to be interpreted like this:
$a = 2; echo ($a == 1 ? 'one' : ($a == 2 ? 'two' : ($a == 3 ? 'three' : ($a == 4 ? 'four' : 'other'))));
However, the PHP ternary operator is strangely left-associative, so your code is actually equivalent to this:
<?php $a = 2; echo (((($a == 1 ? 'one' : $a == 2) ? 'two' : $a == 3) ? 'three' : $a == 4) ? 'four' : 'other');
If this is not yet clear, the assessment will look like this:
echo ((((FALSE ? 'one' : TRUE) ? 'two' : $a == 3) ? 'three' : $a == 4) ? 'four' : 'other'); echo ((( TRUE ? 'two' : $a == 3) ? 'three' : $a == 4) ? 'four' : 'other'); echo (( 'two' ? 'three' : $a == 4) ? 'four' : 'other'); echo ( 'three' ? 'four' : 'other'); echo 'four';
200_success Jul 06 '16 at 18:24 2016-07-06 18:24
source share