Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 bug or can anyone explain why ?

like image 947
amd Avatar asked Jul 11 '12 12:07

amd


People also ask

What is post increment and pre-increment in PHP?

Pre-increment. Increments $a by one, then returns $a . $a++ Post-increment. Returns $a , then increments $a by one.

What is diffrence between ++ i and i ++ in PHP?

Save this answer. Show activity on this post. ++$i is pre-increment whilst $i++ post-increment. pre-increment: increment variable i first and then de-reference.

What is difference between ++$ J and J ++ in PHP?

There is no difference between ++$j and $j++ unless the value of $j is being tested, assigned to another variable, or passed as a parameter to a function.

What is difference between pre and post increment method?

In Pre-Increment, the operator sign (++) comes before the variable. It increments the value of a variable before assigning it to another variable. In Post-Increment, the operator sign (++) comes after the variable. It assigns the value of a variable to another variable and then increments its value.


2 Answers

The answer is "because it's PHP". And PHP doesn't make guarantees about that type of statement (incidentally, neither does C).

Yes, it could be considered wrong, but it's PHP. See this "not a bug" bug report.

like image 61
Borealid Avatar answered Oct 13 '22 20:10

Borealid


Look here for a similar example.

Basically this is what happens:

First ++$i is evaluated. $i is now 2.
$i += 2 + $i++ + ++$i;

Next, $i++ is evaluated. $i is now 3.
$i += 2 + 2 + ++$i;

Next, ++$i is evaluated. $i is now 4.
$i += 2 + 2 + 4;

Lastly the sum is computed:
$i = 4 + 2 + 2 + 4 = 12

like image 26
Keppil Avatar answered Oct 13 '22 20:10

Keppil