Q:

For Loop or While Loop - Efficiency

This may be a stupid question, but how does the efficiency of a while loop compare to that of a for loop?  I've always been taught that if you can use a for loop, then I should.  But what actually is the difference between :
$i = 0;
while($i < 100) {
     echo $i;
     $i++;
} 

compare to:
for($i = 0; $i < 100; $i++) {
    echo $i;
}

I know in these specific examples the difference is like .000000001%, but when we are talking about large complex loops, what is the difference?

A:

I think you're drawing the wrong conclusion from the advice you've been given.
The reason (in this instance at least) to prefer the for construct over the while has nothing to do with efficiency; it's all about writing code that expresses your intentions in a clear and easy to understand manner.
The for places the initial condition, increment, and exit condition all in one place, making it easier to understand. The while loop spreads them around. For example, in your sample, what is the initial value of i? -oh, you forgot to specify it? --that's the point.

A:

That depends on the exact compiler that you use. In your example, a good compiler will create the same machine code for both options.

A:

As you can guess from most of these answers, the main advantage of a for loop over a while loop is readability. A for loop is a lot cleaner and a lot nicer to look at. It's also much easier to get stuck in an infinite loop with a while loop. I would say that I agree with your teachings that if you can use a for loop, you should, so as long as you stick to that, your programming experiences will be much more enjoyable.

