Multiple index variables in PHP foreach loop

2020-01-27 04:13发布

Is it possible to have a foreach loop in PHP with multiple "index" variables, akin to the following (which doesn't use correct syntax)?

foreach ($courses as $course, $sections as $section)

If not, is there a good way to achieve the same result?

8条回答
我命由我不由天
2楼-- · 2020-01-27 04:50

If both the arrays are of the same size you can use a for loop as:

for($i=0, $count = count($courses);$i<$count;$i++) {
 $course  = $courses[$i];
 $section = $sections[$i];
}
查看更多
手持菜刀,她持情操
3楼-- · 2020-01-27 04:55

TRY -

1)

<?php
$FirstArray = array('a', 'b', 'c', 'd');
$SecondArray = array('1', '2', '3', '4');

foreach($FirstArray as $index => $value) {
    echo $FirstArray[$index].$SecondArray[$index];
    echo "<br/>";
}
?>

or 2)

<?php
$FirstArray = array('a', 'b', 'c', 'd');
$SecondArray = array('1', '2', '3', '4');

for ($index = 0 ; $index < count($FirstArray); $index ++) {
  echo $FirstArray[$index] . $SecondArray[$index];
  echo "<br/>";
}
?>
查看更多
登录 后发表回答