Pre-increment and post-increment in PHP

the result of the following statement should give 9: (using java or js or C ++)

i = 1;
i += ++i + i++ + ++i;
//i = 9 now

but in php

the same statements will give 12 ?!

$i = 1;
$i +=  ++$i + $i++ + ++$i;
echo $i;

is this a mistake or can anyone explain why?

+5
source share
5 answers

The answer is "because it's PHP." And PHP makes no guarantees regarding this type of operator (by the way, and C).

Yes, it can be considered wrong, but it is PHP. See the error report "no error" .

+7
source

Look here for a similar example.

This is basically what happens:

The first one is evaluated ++$i. $inow equals 2.
$i += 2 + $i++ + ++$i;

Further evaluated $i++. $inow 3.
$i += 2 + 2 + ++$i;

++$i. $i 4.
$i += 2 + 2 + 4;

, :
$i = 4 + 2 + 2 + 4 = 12

+7

According to the documents Operator Priority :

// mixing ++ and + produces undefined behavior
$a = 1;
echo ++$a + $a++; // may print 4 or 5

So, I guess what happens:

$i +=  ++$i + $i++ + ++$i;

Translated to

$i = (++$i + $i++ + ++$i) + $i;

In this case, it will contain up to 12.

+4
source

There are no guarantees as to what these increments are. Why write two-dimensional code?

+2
source

Java, JS, or C ++ evaluate this equation as follows:

i = 1;

i += ++i + i++ + ++i; --> i = i* + ++i + i++ + ++i (i* is 1 all the time)

But in PHP:

$i = 1;

$i += ++$i + $i++ + ++$i; --> $i = $i* + ++$i + $i++ + ++$i ($i* is calculated after increments, in your situation $i* is 4)

The difference is what I think.

+1
source

All Articles