Ternary operator left associativity

Kapil Sharma picture Kapil Sharma · Dec 13, 2013 · Viewed 11.1k times · Source

In the PHP manual, I find the following 'user contributed note' under "Operators".

Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.

You cannot write code like this (as you may have accustomed to in C/C++):

<?php 
$a = 2; 
echo ( 
    $a == 1 ? 'one' : 
    $a == 2 ? 'two' : 
    $a == 3 ? 'three' : 
    $a == 4 ? 'four' : 'other'); 
echo "\n"; 
// prints 'four' 

I actually try it and it really prints four. However I could not understand the reason behind it and still feel it should print two or other.

Can someone please explain what is happening here and why it is printing 'four'?

Answer

200_success picture 200_success · Jul 6, 2016

In any sane language, the ternary operator is right-associative, such that you would expect your code to be interpreted like this:

$a = 2;
echo ($a == 1 ? 'one' :
     ($a == 2 ? 'two' :
     ($a == 3 ? 'three' :
     ($a == 4 ? 'four' : 'other'))));    # prints 'two'

However, the PHP ternary operator is weirdly left-associative, such that your code is actually equivalent to this:

<?php
$a = 2;
echo (((($a == 1  ? 'one' :
         $a == 2) ? 'two' :
         $a == 3) ? 'three' :
         $a == 4) ? 'four' : 'other');   # prints 'four'

In case it still isn't clear, the evaluation goes 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';