Why $x=5; $x+++$x++; equals with 11 in PHP?

  • A+
Category:Languages

According to the opcodes it should be 12. Am I getting it wrong?

number of ops:  8 compiled vars:  !0 = $x line    #* E I O op                  fetch      ext   return  operands -------------------------------------------------------------------------   3     0  E >   EXT_STMT                                                          1        ASSIGN                                         !0, 5   5     2        EXT_STMT                                                          3        POST_INC                               ~2      !0         4        POST_INC                               ~3      !0         5        ADD                                    ~4      ~2, ~3         6        ECHO                                           ~4   7     7      > RETURN                                         1  branch: #  0; line:     3-    7; sop:     0; eop:     7; out1:  -2 path #1: 0, 

Edit

Also ($x++)+($x++); returns the same result (11).

 


It took me a few reads, but I think it works like this:

In the case of a $x++, it first 'gets used', then increase:

  • Set $x to 5
  • Place $x onto stack (which is 5)
  • Increment ($x is now 6)
  • Add $x onto stack (which adds 6, so 5+6 -> $x=11)
  • Adding is done, that outcome is 11
  • Increment $x (which is isn't used further, but $x is now 12)

Actually, in this specific example, if you would echo $x; it would output 7. You never reassign the value back to $x, so $x=7 (you incremented it twice);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: