0

in php

$var =  true ? '1' : false ? '2' : false ? '3' : '4';
echo $var;

output is 3

in Java

char cond =  true ? '1' : false ? '2' : false ? '3' : '4';
System.out.println( cond );

output is 1

I completely understand how Java performed the logic. but i can't get how php will output 3. need help to understand how php actually evaluated that.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Loon Yew
  • 51
  • 1
  • 7
  • Yes. i tried run in both php and java – Loon Yew Jul 01 '14 at 03:47
  • 2
    I just answered a question about this a few weeks ago: http://stackoverflow.com/questions/24040555/php-calculation-why-is-11-3/24040704#24040704 – p.s.w.g Jul 01 '14 at 03:48
  • That is funky! Expanding the if conditions gives the desired 1 - https://eval.in/168248. Thanks @p.s.w.g for your link aswell! – Darren Jul 01 '14 at 03:51
  • 2
    @Darren Simply putting parentheses around the latter clauses should work too: `true ? '1' : ( false ? '2' : ( false ? '3' : '4' ) )` – p.s.w.g Jul 01 '14 at 03:54

1 Answers1

0

Precedence with parentheses

$var =  ((true ? '1' : false) ? '2' : false) ? '3' : '4';
echo $var;

Documentation: http://php.net/language.operators.comparison#example-138

Some explanation: https://bugs.php.net/bug.php?id=61915

sectus
  • 15,605
  • 5
  • 55
  • 97