Shagun Sodhani
Shagun Sodhani

Reputation: 3727

strange behaviour of php

Today I noticed an ambiguity in php. I ran this code

$i = 5;
$i = $i ++;
var_dump($i); //output 5 instead of 6 

Let us assume the initial value of $i is 5. Now the new value should be 6 but it in fact turns out to be 5. When I did the same thing in C++ I got 6 as expected. Is it some bug in php which went unnoticed for so many years or is it some thing else. Can some one please explain it?

Upvotes: 1

Views: 90

Answers (3)

Grambot
Grambot

Reputation: 4524

Check out the manual for incrementation/decrementation operators. The behavior you ask is normal, just goes against your intuition as a C++ developer.

$i++ first returns the value of $i then executes and increment while ++$i increments $i before returning it.

Upvotes: 1

dan-lee
dan-lee

Reputation: 14502

Try

$i = ++$i;

and you'll get the right result.

The problem is that if you do $i = $i++ then $i is incremented after the statement but you are assigning it to the old on the other side, so it never gets to increment the variable

Upvotes: 3

deceze
deceze

Reputation: 522165

Why do you assume the value should be 6?

$i is being incremented, the value before the incrementing is returned (because you're using the post increment operator) and assigned to $i. Seems logical.

Upvotes: 5

Related Questions