asmith Posted January 10, 2008 Share Posted January 10, 2008 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 https://forums.phpfreaks.com/topic/85419-foreach-for-2-arrays/ Share on other sites More sharing options...
wildteen88 Posted January 10, 2008 Share Posted January 10, 2008 No. Foreach can only loop 1 array at a time. Could you explain more on what you're trying to do? Link to comment https://forums.phpfreaks.com/topic/85419-foreach-for-2-arrays/#findComment-435817 Share on other sites More sharing options...
asmith Posted January 10, 2008 Author Share Posted January 10, 2008 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 https://forums.phpfreaks.com/topic/85419-foreach-for-2-arrays/#findComment-435824 Share on other sites More sharing options...
rhodesa Posted January 10, 2008 Share Posted January 10, 2008 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 https://forums.phpfreaks.com/topic/85419-foreach-for-2-arrays/#findComment-435831 Share on other sites More sharing options...
rhodesa Posted January 10, 2008 Share Posted January 10, 2008 that was lazy of me....the if should be: if($key1 === FALSE || $key2 === FALSE || $key3 === FALSE) break; Link to comment https://forums.phpfreaks.com/topic/85419-foreach-for-2-arrays/#findComment-435833 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.