2

Possible Duplicate:
for vs foreach vs while which is faster for iterating through arrays in php

For each and while, which of these is faster, recommended, and what are their resource usages like?

2
  • 6
    If this is a true concern, I suspect you're using the wrong language and platform.
    – falstro
    Dec 27, 2010 at 8:00
  • @amphetamachine, these wheels are carrying most of top top rated sites, lol :) The key word here is "true concern". The thing you really need is not a program language, but a programmer. endangered species novadays... Dec 27, 2010 at 8:16

3 Answers 3

2

foreach is optimized for iteration over collections. That's a fancy way of saying that it works best (and fastest) when you use it with arrays (and as of PHP5, objects). You can use while() to get the same effect as a foreach, but its not as efficient since you need to call list() inside the while loop.

foreach($array as $key => $value) written with a while is while(list($key,$value) = each($array)). You can see the number of extra calls that are needed.

5
  • +1. The big downside of foreach is that you can't navigate within the collection, and you don't know when you've reached its end.
    – Pekka
    Dec 27, 2010 at 8:01
  • 2
    The foreach loop will perform the same calls, only it is hidden from your eyes. Shorter code is not necessarily faster (although it might be, in this case).
    – GolezTrol
    Dec 27, 2010 at 8:04
  • @Pekka not that big. And, still, the question itself is stupid one, you know. Dec 27, 2010 at 8:27
  • @Col well, it is a big downside if you need to navigate inside the array. But I agree, the performance differences are really irrelevant
    – Pekka
    Dec 27, 2010 at 8:31
  • @Pekka dunno what do you mean by "navigate", but if it's not "iterate" then foreach is just wrong tool for this Dec 27, 2010 at 8:48
1

i think they should have the same speed. i prefer foreach because its safer.

1

That may depend on how you use them exactly. You can choose to pass an array by reference to the foreach loop. In that case there will not be made a copy of the entire array. Optimizations like this probably have more effect than choosing between foreach and while.

Not the answer you're looking for? Browse other questions tagged or ask your own question.