I learnt something today. Something so trivial I don’t know why I did not know this before today.
The last part of the for loop is evaluated AFTER the body of the loop has executed. Which means whether you use post increment or pre increment the number of loops remain the same.
This, it now seems, makes pre increment slightly better because it requires no temporary variable.
@TerribleWaste , wacha nikuchekelee kidogo and also ask you a stupid question.
Kwani you have never stepped through your code before, how do you debug.
I will give you a like and leave you with probably the most important piece of advice i can give you. “IN SOFTWARE ENGINEERING, THE MOST IMPORTANT THING TO UNDERSTAND IS WHY AND NOT HOW”
I never really paid attention, I guess. I’ve always used the post increment and the VS debugger sort of jumps through the line quickly I never noticed when the index variable has changed. I guess it’s hard to see something if you’re not looking for it. Never too late to learn though.
I think there is no difference in the number of loops since the compiler subtly changes any pre-increment to post-increment, contrary to your conclusion.
Therefore if you provided pre-increment, the compiler will go an extra mile to optimize it before executing the body. Post-increment on the other hand requires no further optimization and the compiler will therefore just jump straight into executing the body.
This makes sense because from the basics of php, statements get executed line by line (lines are separated by semi-colons) and I therefore don’t think that the increment gets executed after the body in the code you provided. If that were the case, it would contrast this very rule of php.
How is it then that zero gets printed. If the index was incremented before the body of the loop was executed on pre increment $i would be == 1 before the body is executed. Right?
You are right. I think because post-increment doesn’t really change the value of a variable until the next time it’s evaluated which will be when the loop comes back around after executing the body.
Just to clarify: When I said pre increment I meant ++$i, and post increment => $i++
I was a little confused by what @kukufry said about compiler optimizations but I now see what you meant.