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:34

No, because those arrays may have other number of items.

You must explicitely write something like that:

for ($i = 0; $i < count($courses) && $i < count($sections); ++$i) {
    $course = $courses[$i];
    $section = $sections[$i];

    //here the code you wanted before
}
查看更多
Viruses.
3楼-- · 2020-01-27 04:38

to achieve just that result you could do

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

but that only works for two arrays

查看更多
趁早两清
4楼-- · 2020-01-27 04:38

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];
}
查看更多
叛逆
5楼-- · 2020-01-27 04:38

No, this is maybe one of the rare cases PHP's array cursors are useful:

reset($sections);
foreach ($courses as $course)
{
 list($section) = each($sections);
}
查看更多
聊天终结者
6楼-- · 2020-01-27 04:39

What would that do, exactly? Are $courses and $sections just two separate arrays, and you want to perform the same function for the values in each? You could always do:

foreach(array_merge($courses, $sections) as $thing) { ... }

This makes all the usual assumptions about array_merge, of course.

Or is it that $sections comes from $course and you want to do something for each section in each course?

foreach($courses as $course) {
    foreach($sections as $section) {
        // Here ya go
    }
}
查看更多
够拽才男人
7楼-- · 2020-01-27 04:47

like this?

foreach($array as $b=>$c){

}
查看更多
登录 后发表回答