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

<p>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?</p>

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


foreach ($array as $index =&gt; $value)
{
    # code...
}


do
{
    # code...
}
while ($flag == false);
</code></pre>

[{'answer_id': 22806, 'author': 'Thomas Owens', 'author_id': 572, 'author_profile': 'https://Stackoverflow.com/users/572', 'pm_score': 0, 'selected': False, 'text': "<p>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.</p>\n\n<p>I'm not sure of any performance benefits, though.</p>\n"}, {'answer_id': 22810, 'author': 'wvdschel', 'author_id': 2018, 'author_profile': 'https://Stackoverflow.com/users/2018', 'pm_score': 0, 'selected': False, 'text': "<p>Performance is not significantly better in either case. While is useful for more complex tasks than iterating, but <code>for</code> and <code>while</code> are functionally equivalent.</p>\n\n<p><code>Foreach</code> is nice, but has one important caveat: you <strong>can't modify</strong> 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.</p>\n"}, {'answer_id': 22811, 'author': 'mercutio', 'author_id': 1951, 'author_profile': 'https://Stackoverflow.com/users/1951', 'pm_score': 0, 'selected': False, 'text': "<p>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:</p>\n\n<pre><code>while(list($key, $value) = each($array)) {\n</code></pre>\n\n<p>But that approach is particularly ugly for a simple small structure.</p>\n\n<p>while loops are better suited for looping through streams, or as in the following example that you see very frequently in PHP:</p>\n\n<pre><code>while ($row = mysql_fetch_array($result)) {\n</code></pre>\n\n<p>Almost all of the time the different loops are interchangeable, and it will come down to either a) efficiency, or b) clarity.</p>\n\n<p>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.</p>\n"}, {'answer_id': 22813, 'author': 'juan', 'author_id': 1782, 'author_profile': 'https://Stackoverflow.com/users/1782', 'pm_score': 0, 'selected': False, 'text': '<p>In regards to performance, a foreach is more consuming than a for</p>\n\n<p><a href="http://forums.asp.net/p/1041090/1457897.aspx" rel="nofollow noreferrer">http://forums.asp.net/p/1041090/1457897.aspx</a></p>\n'}, {'answer_id': 22832, 'author': 'jj33', 'author_id': 430, 'author_profile': 'https://Stackoverflow.com/users/430', 'pm_score': 1, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 22838, 'author': 'Andy', 'author_id': 1993, 'author_profile': 'https://Stackoverflow.com/users/1993', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.php.lt/benchmark/phpbench.php" rel="nofollow noreferrer">PHP Benchmarks</a></p>\n'}, {'answer_id': 22844, 'author': 'JeremiahClark', 'author_id': 581, 'author_profile': 'https://Stackoverflow.com/users/581', 'pm_score': 0, 'selected': False, 'text': '<p>Each looping construct serves a different purpose.</p>\n\n<p>for - This is used to loop for a specific number of iterations.  </p>\n\n<p>foreach - This is used to loop through all of the values in a collection.</p>\n\n<p>while - This is used to loop until you meet a condition.</p>\n\n<p>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).</p>\n\n<pre><code>$count = 0;\ndo\n{\n   ...\n   $count++;\n}\nwhile ($count &lt; 10);  \n</code></pre>\n\n<p>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.  </p>\n'}, {'answer_id': 23024, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 1, 'selected': False, 'text': '<p>@brendan:</p>\n\n<p>The article you cited is seriously outdated and the information is just plain wrong. Especially the last point (use <code>for</code> instead of <code>foreach</code>) is misleading and the justification offered in the article no longer applies to modern versions of .NET.</p>\n\n<p>While it\'s true that the <code>IEnumerator</code> uses virtual calls, these <em>can</em> actually be inlined by a modern compiler. Furthermore, .NET now knows generics and strongly typed enumerators.</p>\n\n<p>There are a lot of performance tests out there that prove conclusively that <code>for</code> is generally no faster than <code>foreach</code>. <a href="http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx" rel="nofollow noreferrer">Here\'s an example</a>.</p>\n'}, {'answer_id': 23739, 'author': 'Paige Ruten', 'author_id': 813, 'author_profile': 'https://Stackoverflow.com/users/813', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n<p>With a foreach loop, a copy of the original array is made in memory to use inside.</p>\n<p>Foreach is nice, but has one important caveat: you can't modify the enumerable you're iterating.</p>\n</blockquote>\n<p>Both of those won't be a problem if you pass by reference instead of value:</p>\n<pre><code> foreach ($array as &amp;$value) {\n</code></pre>\n<p>I think this has been allowed since PHP 5.</p>\n"}, {'answer_id': 23750, 'author': 'Jared Updike', 'author_id': 2543, 'author_profile': 'https://Stackoverflow.com/users/2543', 'pm_score': 0, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 23835, 'author': 'Imran', 'author_id': 1897, 'author_profile': 'https://Stackoverflow.com/users/1897', 'pm_score': 4, 'selected': True, 'text': '<p>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 </p>\n\n<p>The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9;</p>\n\n<pre><code>for ($i = 0; $i &lt; 10; $i++)\n{\n        # code...\n}\n</code></pre>\n\n<p>Same thing done with while loop:</p>\n\n<pre><code>$i = 0;\nwhile ($i &lt; 10)\n{\n    # code...\n    $i++\n}\n</code></pre>\n\n<p>Do-while loop is exit-condition loop. It\'s guaranteed to execute once, then it will evaluate condition before repeating the block</p>\n\n<pre><code>do\n{\n        # code...\n}\nwhile ($flag == false);\n</code></pre>\n\n<p>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.</p>\n\n<pre><code>foreach ($array as $index =&gt; $value)\n{\n        # code...\n}\n</code></pre>\n\n<p>You could do the same thing with while loop, like this </p>\n\n<pre><code>while (current($array))\n{\n    $index = key($array);  // to get key of the current element\n    $value = $array[$index]; // to get value of current element\n\n    # code ...  \n\n    next($array);   // advance the internal array pointer of $array\n}\n</code></pre>\n\n<p>And lastly: <a href="http://www.php.net/download-docs.php" rel="noreferrer">The PHP Manual</a> is your friend :)</p>\n'}]
['https://Stackoverflow.com/questions/22801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384652/']