Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP calculation - why is 1+1=3? [duplicate]

Tags:

php

The code my friend sends me is:

echo '1+1='.(1+1==2?2:1+2==2?3:2); 

Why is it 3?

like image 679
Ismail Avatar asked Jun 04 '14 14:06

Ismail


1 Answers

PHP's evaluation of the ternary (or conditional) operator is a bit different from that of other languages.

1+1==2 ? 2 : 1+2==2 ? 3 : 2 

Most languages (e.g. JavaScript) would evaluate this as:

(1+1==2) ? (2) : ( (1+2==2) ? (3) : (2) )  => 2 

PHP, however, evaluates this as:

( (1+1==2) ? (2) : (1+2==2) ) ? (3) : (2) => 3 

So because (1+1==2) evaluates to true, the result of the first ternary expression evaluates to 2, and that result is then passed to the second ternary expression, which evaluates to 3.

This behavior is alluded to in the documentation:

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…

The Wikipedia article on the ?: operator also mentions this:

Due to an unfortunate error in the language grammar, the implementation of ?: in PHP uses the incorrect associativity when compared to other languages…

The reason is that nesting two conditional operators produces an oversized condition with the last two options as its branches: c1 ? o1 : c2 ? o2 : o3 is really ((c1 ? o1 : c2) ? o2 : o3). This is acknowledged and will probably not change.

  • See also: Bug #61915
like image 85
p.s.w.g Avatar answered Sep 19 '22 18:09

p.s.w.g