How do you loop though an non-associative arrays?

Often, I see people loop though non-associative arrays like this:

for($i=0;$i<count($array);$i++){
//do stuff to $array[$i];
}

List of my initial thoughts

so I would rewrite it as

 $count = count($array):
while($i<$count){
	//do stuff to $array[$i]
	++$i;
}

Ok, now many people would start moaning about how while loop is evil since for loop is easier to understand and takes less lines. use for loop if you want...

Usually, I would stop optimize since I can't see anything that can increase the speed. This morning, I had to test one of my thoughts about loop the array backward, so I got something like this:

 $count = count($array):
$i = $count;
while($i){
--$i;	
//do stuff to $array[$i]
 
}

This is the most optimized loop yet, one less comparison ($i<$count)
BIG DEAL!
benchmark the non optimized code with the last one, loop though 10000 key array. The non optimized loop is 3 times slower than the most optimized version.

What about foreach?

Adam D. Ruppe's picture

Why wouldn't you write

foreach(){
 
}

for any array? It should work on all of them, and is IMO a little easier to understand. Is it even worse than for()?

But, if for is actually slower than while, it means php must be even more broken than I thought; there should be no reason for that. Any worthwhile compiler (PHP is compiled, just on the fly, how I understand it) should cache the result of length($array), and memory usage should be the same; all three loop types in any sane environment would be exactly the same.

Foreach is a very slow loop

Mgccl's picture

Foreach is a very slow loop and I only see associative arrays when I'm working with db queries, so I don't think there is point use Foreach for everything. Also, some loops you want to do something with the previous or next element in the array.

Usually, people make associative arrays as objects.

I don't know about the length($array) should be cached. the length of the array can change.
You might be right, I'm not an expert in the PHP interpreter.

Thanks for that, most of

Peter Goodman's picture

Thanks for that, most of those things I didn't know. I remember reading about the $i++ versus ++$i, although I had never applied it (unless I explicitly needed ++$i). Besides that, I have now started applying these rules to my code :)

Well, usually, if you apply

Mgccl's picture

Well, usually, if you apply all these techniques, your application might get 10% gain in speed.
Sometimes, finding the better way of doing something gives me 650 times faster application. For example the prime spiral one

I was thinking over this

Peter Goodman's picture

I was thinking over this post last night and was wondering which of the following is fastest for looping over iterators...

$it->rewind();
while($it->valid()) {
	$current = $it->current();
	$it->next();
}

$it->rewind();
for($i = $it->key(); $it->valid(); $it->next()) {
	$current = $it->current();
}

foreach($it as $current) {
 
}

They are all essentially the same thing because all five functions are implicitly/explicitly called.

I'm going to test that

Mgccl's picture

I'm going to test that pretty soon...
Things becomes tricky when objects are evolved.

optimized while loop not correct?

tauven's picture

Hi, i think the optimized while loop is not working as you expect.
you never come to array[0] because the while condition will not evaluate to true if $i == 0.
it should work if you use while (-1 != $i) { ... }
question would be if it is then still faster than the other ways.

ciao,
tauven

I updated it, thx! $count =

Mgccl's picture

I updated it, thx!

$count = count($array):
$i = $count;
while($i){
--$i;   
//do stuff to $array[$i]
 
}

it is still as fast. it does count($array) amount of loop now.

Post new comment

The content of this field is kept private and will not be shown publicly.
If you have a Gravatar account, used to display your avatar. If you have a Gravatar account, used to display your avatar.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <span> <fn>
  • Lines and paragraphs break automatically.
  • Textual smileys will be replaced with graphical ones.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.

More information about formatting options

What is 20 + 49?
To combat spam, please solve the math question above.
Honey Pot that kill bots