Posted by:

for($i = 0; $i<=5; $i++){ echo $i."<br>"; } 

got the result:

 0 1 2 3 4 5 

so:

 for($i = 0; $i<=5; ++$i){ echo $i."<br>"; } 

got the result:

 0 1 2 3 4 5 

As you can see, the results are identical.

So what is the difference between the postfix and the prefix increment in this case (in the for loop)?

  • And if in fact, the postfix and the prefix work in operations with different execution priorities where there is an opportunity to set a different calculation priority. And in the for loop, this situation cannot arise, so it works. - Dmitry Gvozd

3 answers 3

The difference between the postfix and prefix increment operators is the return value of the expression. Since the results of expressions are not used in the examples given for cycles, there is no difference for cycles. In cycles, the values ​​of the $i variable are used after the calculation of expressions with increments.

Compare your for loops with while loops

 $i = 0; while ( ++$i <= 5 ){ echo $i."<br>"; } 

and

 $i = 0; while ( $i++ <= 5 ){ echo $i."<br>"; } 

In these cycles, the results of expressions with increment are already used.

There was a time when the question of how to write an increment expression in a for loop either as $i++ or ++$i was of great interest from the point of view of code optimization in various programming languages. But now compilers and interpreters are so advanced that they usually generate the same object code when the value of an expression is not used.

    Why do you think that in this case there will be a difference?
    The benefits of these forms are visible only if you need to change the order of execution in the composite instruction.

    Example:
    The increment has a higher priority than the pros / cons, so the calculation will already be with the incremented value:

     $i = 0; 5 +++ $i; // 6 

    Here, first, the result will be calculated, only then the increment will occur:

     $i = 0; 5 + $i++; // 5 

    In your case, only one instruction is executed (actually, the increment itself), so there is no difference.

      In this case, there is no difference

      http://www.php.su/learnphp/operators/?prior Link to the answer to the author's question

      • one
        Links to external resources are fine, but leave the description with the link so that other users have an idea of ​​its contents. Always quote the most necessary information that you have taken from the indicated source, in case it is unavailable or permanently closed. - Vadim Prokopchuk