Jump to content

for each loop


BlueM
Go to solution Solved by requinix,

Recommended Posts

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:

 

applefruit
appleveggie
appletree
carrotfruit
carrotveggie
carrottree
pinefruit
pineveggie
pinetree

 

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 by BlueM
Link to comment
Share on other sites

  • Solution

*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
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.