streetparade streetparade - 3 months ago 30
PHP Question

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

which one is the fastest for iterating through arrays in php? or does another exist which is also faster for iterating through arrays?

Answer Source

Even if there is any kind of difference, that difference will be so small it won't matter at all.

If you have, say, one query to the database, it'll take so long compared to the loop iterating over the results that the eternal debate of for vs foreach vs while will not change a thing -- at least if you have a reasonable amount of data.

So, use :

  • whatever you like
  • whatever fits your programming standard
  • whatever is best suited for your code/application

There will be plenty of other things you could/should optimize before thinking about that kind of micro-optimization.

And if you really want some numbers (even if it's just for fun), you can make some benchmark and see the results in practice.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download