BlueM Posted August 5, 2015 Share Posted August 5, 2015 (edited) 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>"; }} ?> Edited August 5, 2015 by BlueM Quote Link to comment Share on other sites More sharing options...
Solution requinix Posted August 5, 2015 Solution 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 Quote Link to comment 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>"; 2 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.