Looping multiple arrays simultaneously
Doing a homework assignment and I'm not sure I can wrap my mind around how to go about this problem. I have two arrays with the same amount of values:
$monthsShort = array("Jan", "Feb", ..., "Nov", "Dec");
$monthsLong = array("January", "开发者_C百科February", ..., "November", "December");
I need a loop that will traverse both of them and generate output that looks like this:
1 Jan January
2 Feb February
...
12 Dec December
I'm just really not sure where to begin as I can't find a similar problem in my textbook. I did find this: Foreach loop with multiple arrays, but I am not sure how/why it works. Any help is greatly appreciated.
for ($i = 0; $i < 12; $i++) {
$p = $i+1;
echo "$p {$monthsShort[$i]} {$monthsLong[$i]}";
}
You can get a single index of an array by using this syntax:
$myArray = array("Jan", "Feb", "etc.");
echo $myArray[0]; // prints "Jan"
echo $myArray[1]; // prints "Feb"
The only trick is that you want the indexes to be a variable too, which you can use a for
loop for. This will print "JanFebetc.":
for($i = 0; $i < count($myArray); $i++) {
echo $myArray[$i];
}
Those two together should let you loop through both arrays at the same time.
The example you have picked is for arrays inside arrays, you actually have two arrays you would like to iterate over at once. That's something different.
You can first combine both arrays with array_map
Docs and then iterate over the new array:
$monthsShort = array("Jan", "Feb", '...', "Nov", "Dec");
$monthsLong = array("January", "February", '...', "November", "December");
$map = array_map(NULL, $monthsShort, $monthsLong);
foreach($map as $month => $value)
{
list($short, $long) = $value;
printf("%d %s %s\n", $month+1, $short, $long);
}
See the demo. As often in programming, there are more than one solution to a problem, I choose array_map
to easily iterate over one array.
$index = 0;
foreach ($monthsShort as $month) {
echo $index+1 . " " . $month . " " . $monthsLong[$index] . "\n";
$index++;
}
Easy!
I would do this using a for
loop, as you can see below:
for($i = 0; $i < 12; $i++)
{
printf("%d %s %s<br />\n", $i + 1, $monthsShort[$i], $monthsLong[$i]);
}
$output = '';
$count = count($monthsShort);
for ($i = 0; $i < $count; $i++) {
$output .= $i . ' ' . $monthsShort[$i] . ' ' . $monthsLong[$i] . '<br />';
}
echo $output;
Use the count function to count the items in the array
<?php
$monthsShort = array("Jan", "Feb", "Nov", "Dec");
$monthsLong = array("January", "February", "November", "December");
for($i=0;$i<count($monthsLong);$i++){
echo $i." ".$monthsShort[$i]." ".$monthsLong[$i]."\n";
}
?>
Outputs
0 Jan January
1 Feb February
2 Nov November
3 Dec December
精彩评论