BlueM Posted August 5, 2015 Share Posted August 5, 2015 Hey guys this is pretty simple i guess but i need some help. I am trying to output both information from the arrays but without doing the loop twice. this is my output: applefruitappleveggieappletreecarrotfruitcarrotveggiecarrottreepinefruitpineveggiepinetree but I would like to have an output like : applefruit carrotveggie pinetree here is my code <?php $first="apple,carrot,pine"; $second="fruit,veggie,tree"; $array1=explode(",", $first); $array2=explode(",", $second); foreach($array1 as $number1) { foreach($array2 as $number2) { echo $number1.$number2."</br>"; }} ?> Link to comment https://forums.phpfreaks.com/topic/297637-for-each-loop/ Share on other sites More sharing options...
requinix Posted August 5, 2015 Share Posted August 5, 2015 *thrice Code inside a loop executes once for every time in the loop. Code inside a loop inside a loop executes once for every time in one loop and again for every time in the other loop. 3 fruit * 3 other things = 9 times total. PHP doesn't have a loop you can use for multiple arrays at once, so you have to do it yourself. The job is easier with functions like reset, key, current, and next. (There are other ways too.) $first = "apple,carrot,pine"; $second = "fruit,veggie,tree"; $array1 = explode(",", $first); $array2 = explode(",", $second); reset($array1); reset($array2); while (key($array1) !== null && key($array2) !== null) { $number1 = current($array1); $number2 = current($array2); echo $number1, $number2, "<br>"; next($array1); next($array2); } 3v4l.org/gmc2T Link to comment https://forums.phpfreaks.com/topic/297637-for-each-loop/#findComment-1518045 Share on other sites More sharing options...
Barand Posted August 5, 2015 Share Posted August 5, 2015 or you could combine the two arrays $array3 = array_combine($array1, $array2); foreach ($array3 as $k=>$v) echo "$k$v<br>"; Link to comment https://forums.phpfreaks.com/topic/297637-for-each-loop/#findComment-1518060 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.