Jump to content

foreach for 2 arrays


asmith

Recommended Posts

can i use something like foreach function for 2 arrays at the same time ? 

 

i want to have a loop which each time one from first array and one from second array be chosen .

 

something like :

 

foreach ($arr1 as $val1 AND $arr2 as $val2)

 

thanks

Link to comment
Share on other sites

on this forum , i remember i wanted to solve some other guys question , but my solution needed to loop 2 arrays at the same time,so i couldn't answer him .

now i was just wondering if i want to loop more than 1, maybe more than 3 arrays at the same time , but would be the easiest way ?

 

hmm

 

$arr1 = array(2 => 34,6 => 23,12 => 76);
$arr2 = array(54 = > 2,14 => 97,2 => 44);
$arr3 = array(8=> 3,67 => 21,26 => 34);

 

hmmm each array value multiply on its key + the same with second + the same with third,  add all final numbers together.

 

i'm typing write now.. i mean your question made me show that example, maybe the solution is easy .  how YOU do it with loops ?

 

 

 

 

 

Link to comment
Share on other sites

you could use each()

 

$arr1 = array(2 => 34,6 => 23,12 => 76);
$arr2 = array(54 = > 2,14 => 97,2 => 44);
$arr3 = array(8=> 3,67 => 21,26 => 34);
while(1){
  list($key1,$val1) = each($arr1);
  list($key2,$val2) = each($arr2);
  list($key3,$val3) = each($arr3);
  if(!$key1 || !$key2 || !$key3) break;

  ...do work here...
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.