Multiple index variables in PHP foreach loop

Solution 1:

to achieve just that result you could do

foreach (array_combine($courses, $sections) as $course => $section)

but that only works for two arrays

Solution 2:

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];
}

Solution 3:

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/>";
}
?>

Solution 4:

You would need to use nested loops like this:

foreach($courses as $course)
{
    foreach($sections as $section)
    {
    }
}

Of course, this will loop over every section for every course.

If you want to look at each pair, you are better off using either objects that contain the course/section pairs and looping over those, or making sure the indexes are the same and doing:

foreach($courses as $key => $course)
{
    $section = $sections[$key];
}