Ben Fortune
Ben Fortune

Reputation: 32127

Is there any actual difference between the following for and while statements?

Say we have the following, for example's sake. Is there any performance difference, usage difference between the following, or is it just a personal preference?

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

and

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

Upvotes: 0

Views: 81

Answers (2)

Tomas Creemers
Tomas Creemers

Reputation: 2715

No. Any for loop can be written as a while loop (and vice versa). The same way, each recursive function can be written as a loop (sometimes with a lot of work, but it can be done) and vice versa.

Regarding performance: while I have not benchmarked this, both loops declare exactly the same variables at the same time, execute the same instructions at the same time and peform the same comparison at the same time. After the loop is complete, the same variable ($i in your example) exists with the same value. I don't see where any performance difference would come from. (Note that in some other languages, like C++, the variable declared in the initialization part of the for loop stops existing after the loop.)

Which loop you use is mostly a matter of personal preference. I like to use for loops when the number of iterations is known (like in your example: 10 iterations). When the loop has to go on until some condition (that you cannot predict when writing the program) is met, like when iterating over a database result set of which you don't know the size, I usually use a while loop.

Upvotes: 1

Laurence Frost
Laurence Frost

Reputation: 2993

The only difference is variable scoping (depending on the programming language).

For example, you may want $i to only have scope within the for loop, this can be achieved.

This cannot be done the same with a while loop, but other than that they are the same.

One may yield an extremely marginal performance advantage over the other, but this would be specific to the compiler. It would be so small that code preference would take priority every time though.

Upvotes: 0

Related Questions