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.

In that loop you have made

Peter Goodman's picture

In that loop you have made the assumptuon that $a and $b have the same number of array elements, so why not simply do:

while($tmp_a = each($a) && $tmp_b = each($b));

you could even use an || in there if you want to account for arrays with a differing number of elements. I suggest this because your current approach to the problem is still kludgy when you increase the numbers of associative arrays you loop over. Consider that you handle $a in one way, and every other array in a different way. It would seem more practical to handle them all in the same way, no?

Great, that looks like a

Mgccl's picture

Great, that looks like a better idea..
finally I get to see the while loop I love :)

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 44 + 28?
To combat spam, please solve the math question above.
Honey Pot that kill bots