Jump to content

Why difference in outputs?


684425

Recommended Posts

Actually the question was asked in a facebook group. and my answer there was...

You ignored variable $p in second code and directly called an output of $i so it became $i = 2; $i++; for php.
In your 1st code you are trying to do the same thing, but because of only one variable $i on both sides in 2nd line, php ignored #YOU and did it work. 
1st code
$i = 2; //declared an assigned a value.
$i = $i++; //another declaration.
------------------------------------
2nd code
$i = 2; //declared an assigned a value.
$i++; // direct increment.

Still i was confused... Thanks dear for reply :)

Explained by a friend.

$i = $i++;    // internally is more like
$temp = $i++; // $temp = 2; $i=3
$i=$temp;     // $i=2
That doesn't seem to be explaining anything.

 

$i = 2;
$p = $i++;
When you say this, you are assigning $p to the value of $i before $i is incremented. So since the value of $i is 2, $p is equal to 2. After $p is assigned to the value of $i, only then does $i get incremented. On the next statement, $i is equal to 3, since it has then been incremented.

 

Now, when you use the same variable, you are basically overriding the would-be incremented value. So if you say

$i = 2;
$i = $i++;
you are setting $i to the value of $i again before it is incremented, which is 2. Since you're using the same variable name, you're effectively preventing the increment from happening.

 

But if you changed it to ++$i, then you would end up with 3.

$i = 2;
$i = ++$i;
echo $i; // $i = 3
This is because, the increment is evaluated before the assignment happens. So by the time $i gets its new value, the increment has happened and the new value is 3.

 

Hopefully that all came out in a way that makes sense.

 

EDIT: This is kind of what is happening internally when you do $i++ vs $++i.

 

// -- $p = $i++;
$i = 2;
$p = $i;
// $i == 2; $p == 2;
$i = $i + 1;
// $i == 3; $p == 2;


// -- $p = $++i;
$i = 2;
$i = $i + 1;
// $i == 3;
$p = $i;
// $i == 3; $p == 3;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.