Jump to content

How do i create a loop for this?


Brandon_R

Recommended Posts

Hello guys can someone show me how to create a loop for this array echoing out the result. The array is

 

$hello = array("hello", "guys", "hows", "it");

$goodbye = array("Its", "going", "find", "thanks");

$aiight = array("Good", "then", "thats", "well");

 

After the above array is run through the loop the result for each echo should be

 

Hello Its Good

Guys Going Then

Hows find thats

It thanks well.

 

I tried nested foreach loops and the result was catastrophic. It was more like a factorial problem than matching the first element in the array with the first element in the other 2 arrays.

Link to comment
https://forums.phpfreaks.com/topic/176213-how-do-i-create-a-loop-for-this/
Share on other sites

assuming the 3 arrays will always be the same length

$hello = array("hello", "guys", "hows", "it");
$goodbye = array("Its", "going", "find", "thanks");
$aiight = array("Good", "then", "thats", "well");

for ($i = 0; $i < count($hello); $i++){
echo $hello[$i]." ".$goodbye[$i]." ".$aiight[$i]."<br />";
}

 

if they aren't always the same size this won't work as expected

<?php
$count = count($hello);
for($i = 0; $i < $count; $i++) {
  echo $hello[$i] . " " . $goodbye[$i] . " " . $aiight[$i] . '<br />';
}
?>

 

EDIT: D'oh beaten to the punch, oh well, I think my $count method would be slightly more optimised.

I don't see how it would be any more optimised

I think he means because count($hello) won't have to be pre-preformed every loop. The time difference would be so minimal.. it really wouldn't matter. Personally I'd use Mikesta707's method only because there's no need for that additional variable / line when it's going to save 0.000001 second. The general fluctuations in execution time would be considerably larger than the time that might save.

Given they are the same lengths, with the same keys (in this case numerical).. no need for the count($array) in a for statement... thats why they made foreach ;)

$hello = array("hello", "guys", "hows", "it");

$goodbye = array("Its", "going", "find", "thanks");

$aiight = array("Good", "then", "thats", "well");

foreach($hello as $key => $value) {
echo $value.' '.$goodbye[$key].' '.$aiight[$key].'<br>';
}

 

Well - if they aren't the same length what do you want the script to do? Provide a blank space, or re-use another value somewhere?

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.