Jump to content

for each loop


BlueM

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>";


}}
?>

Link to comment
https://forums.phpfreaks.com/topic/297637-for-each-loop/
Share on other sites

*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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.