Question

It's about PHP but I've no doubt many of the same comments will apply to other languages.

Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?

for ($i = 0; $i < 10; $i++)
{
    # code...
}


foreach ($array as $index => $value)
{
    # code...
}


do
{
    # code...
}
while ($flag == false);
Was it helpful?

Solution

For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet

The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9;

for ($i = 0; $i < 10; $i++)
{
        # code...
}

Same thing done with while loop:

$i = 0;
while ($i < 10)
{
    # code...
    $i++
}

Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block

do
{
        # code...
}
while ($flag == false);

foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index.

foreach ($array as $index => $value)
{
        # code...
}

You could do the same thing with while loop, like this

while (current($array))
{
    $index = key($array);  // to get key of the current element
    $value = $array[$index]; // to get value of current element

    # code ...  

    next($array);   // advance the internal array pointer of $array
}

And lastly: The PHP Manual is your friend :)

OTHER TIPS

This is CS101, but since no one else has mentioned it, while loops evaluate their condition before the code block, and do-while evaluates after the code block, so do-while loops are always guaranteed to run their code block at least once, regardless of the condition.

@brendan:

The article you cited is seriously outdated and the information is just plain wrong. Especially the last point (use for instead of foreach) is misleading and the justification offered in the article no longer applies to modern versions of .NET.

While it's true that the IEnumerator uses virtual calls, these can actually be inlined by a modern compiler. Furthermore, .NET now knows generics and strongly typed enumerators.

There are a lot of performance tests out there that prove conclusively that for is generally no faster than foreach. Here's an example.

I use the first loop when iterating over a conventional (indexed?) array and the foreach loop when dealing with an associative array. It just seems natural and helps the code flow and be more readable, in my opinion. As for do...while loops, I use those when I have to do more than just flip through an array.

I'm not sure of any performance benefits, though.

Performance is not significantly better in either case. While is useful for more complex tasks than iterating, but for and while are functionally equivalent.

Foreach is nice, but has one important caveat: you can't modify the enumerable you're iterating. So no removing, adding or replacing entries to/in it. Modifying entries (like changing their properties) is OK, of course.

With a foreach loop, a copy of the original array is made in memory to use inside. You shouldn't use them on large structures; a simple for loop is a better choice. You can use a while loop more efficiently on a large non-numerically indexed structure like this:

while(list($key, $value) = each($array)) {

But that approach is particularly ugly for a simple small structure.

while loops are better suited for looping through streams, or as in the following example that you see very frequently in PHP:

while ($row = mysql_fetch_array($result)) {

Almost all of the time the different loops are interchangeable, and it will come down to either a) efficiency, or b) clarity.

If you know the efficiency trade-offs of the different types of loops, then yes, to answer your original question: use the one that looks the most clean.

Each looping construct serves a different purpose.

for - This is used to loop for a specific number of iterations.

foreach - This is used to loop through all of the values in a collection.

while - This is used to loop until you meet a condition.

Of the three, "while" will most likely provide the best performance in most situations. Of course, if you do something like the following, you are basically rewriting the "for" loop (which in c# is slightly more performant).

$count = 0;
do
{
   ...
   $count++;
}
while ($count < 10);  

They all have different basic purposes, but they can also be used in somewhat the same way. It completely depends on the specific problem that you are trying to solve.

With a foreach loop, a copy of the original array is made in memory to use inside.

Foreach is nice, but has one important caveat: you can't modify the enumerable you're iterating.

Both of those won't be a problem if you pass by reference instead of value:

 foreach ($array as &$value) {

I think this has been allowed since PHP 5.

When accessing the elements of an array, for clarity I would use a foreach whenever possible, and only use a for if you need the actual index values (for example, the same index in multiple arrays). This also minimizes the chance for typo mistakes since for loops make this all too easy. In general, PHP might not be the place be worrying too much about performance. And last but not least, for and foreach have (or should have; I'm not a PHP-er) the same Big-O time (O(n)) so you are looking possibly at a small amount more of memory usage or a slight constant or linear hit in time.

In regards to performance, a foreach is more consuming than a for

http://forums.asp.net/p/1041090/1457897.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top