Discussions

Hi all php experts,
I am very curious to know whether for is goood or foreach is good to iterate over indexed array.

I mean if we want to iterate over integer indexed array then for is good or foreach is good.

And whats the case if we want to iterate over associate array??

Reply

User Comments

  1. DaneMorgan
    a for loop can be more optimized if you know the number of iterations ahead of time and optimize the count value. foreach is better with lists and is good for looping through each element in an array when you don't know the size.
    1. roy123
      well lets take an scenario in which we know the size. Then in this condition for is faster or foreach is faster? I have done some benchmark tests on this but I am getting similar results in terms of speed.
    2. DaneMorgan
      The differences aren't real big, but there are some things you can do to optimize a for loop that you can't do with a foreach loop. do a google search for "for vs foreach" php and you'll see some different ideas. Many with code examples.
  2. DailyBeerReview
    Nerds! But I respect that.
  3. carsonfb
    Unless you are iterating over large arrays or have many levels of nested loops (which should be avoided anyway), you will probably not notice any speed difference.
    1. DaneMorgan
      Well, you won't notice, but if you can measure it.... Man good times!

Add Your Comment

Login to leave a message.