Saturday, September 8, 2007

for - while

Usually, to iterate a code N times you do

for ($a = 0; $a < N; $a++) {

but, thinking a bit, this code can be optimized, because the second and third sentence can be joined, so we get this

for ($a = -1; ++$a < N;) {

Also, you can think it in this way

$a = 0;
while (++$a < N) {

but the previous approach seems (a bit) better, in the practice. This optimization can improve not much your code, we have to keep in mind this is one of the most common iterations, and you can repeat it a lot along your work.

View example

No comments: