array

Loop multiple associative array at the same time

Today, someone in asked me a question in Qunu asked me a question to loop though 2 associative array at the same time.

Suppose, 2 associative arrays, $a and $b. They have some information corresponding to each other according to their position, but they are not numeric arrays, and it is not possible to manipulate one array's value or key to get another array's key.

My suggestion is to loop though 2 arrays with foreach separately, build them as 2 numeric array and then we will have a numeric key to access them.

foreach($a as $key=>$var){
$num_a[] = array($key=>$var);
}
foreach($b as $key=>$var){
$num_b[] = array($key=>$var);
}

Two foreach loops... if there is more arrays like this, there will be a lot more loops. If the key's information want to be preserved,

The qunu user told me a better code, use each().

foreach($a as $akey=>$avar){
$tmpb = each($b);
$bkey = $tmpb['key'];
$bvar = $tmpb['value'];
}

I didn't have time to ask who he was before he quits from the room.

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.

Syndicate content
Honey Pot that kill bots