3

I have checked for loop these two ways, but given same output:

1: Increment use ++$i

for($i=0; $i<10; ++$i){
    echo $i;
}

2: Increment use $i++

for($i=0; $i<10; $i++){
    echo $i;
}

These both code gave this output:

0 1 2 3 4 5 6 7 8 9

We learn ++$i mean pre increment, $i++ mean post increment,

why that post and pre increment not work? can someone please explain me? thank you.

Gayan
  • 2,845
  • 7
  • 33
  • 60
  • Read this: http://stackoverflow.com/questions/6400518/pre-incrementation-vs-post-incrementation – Pupil Dec 09 '14 at 05:23
  • The method of incrementing doesn't affect the behaviour of the `for` loop. The expression in that field will be executed after each loop regardless of what you put in there. Pre and post incrementation work just fine, just not the way you are thinking. – Havenard Dec 09 '14 at 05:38

2 Answers2

1

Value of $i++ and ++$i will be same after evaluation.

As $i++ first evaluate value of $i then increment $i.
And
++$i first increment then evaluate value of $i.

Here in for loop, it follows step
initialization
test condition(if true then execute body/else exit)
increment/decrement

As again its working for a new line, either you use $i++ or ++$i it will be the same.
But if you use it in between the for loop you can see the difference.
Check Link for more details

for example

$i++;  // Or ++$i;
echo $i;

It will give same value in both condition.
But if you use echo $i++; or echo ++$i then you will find difference.

Community
  • 1
  • 1
Himanshu
  • 4,327
  • 16
  • 31
  • 39
0

Pre- and post- incrementing only make a difference when there are other operations happening in the same statement. For example:

$i = 0;
echo ++$i;

Will return 1, as opposed to this:

$i = 0;
echo $i++;

Which will return 0. In the latter case, the increment happens after the echo.

In your original example, the entire statement being executed is either ++$i or $i++. Either way, the order doesn't matter because nothing else is happening.

Mark Madej
  • 1,752
  • 1
  • 14
  • 19