Multiple index variables in PHP foreach loop

前端 未结 8 634
名媛妹妹
名媛妹妹 2020-11-30 04:52

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

forea         


        
8条回答
  •  庸人自扰
    2020-11-30 05:20

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

提交回复
热议问题