Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple index variables in PHP foreach loop

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?

like image 485
Donald Taylor Avatar asked Nov 11 '10 18:11

Donald Taylor


People also ask

Can we use two foreach loop in PHP?

Note − If there are more than 2 arrays, nested 'foreach' loops can be used. Here, 2 arrays have been declared and they are being traversed using the 'foreach' loop. The result is that the respective index of every array is matched and the data at those indices are displayed one next to the other.

Can we use foreach loop for multidimensional array in PHP?

You can simply use the foreach loop in combination with the for loop to access and retrieve all the keys, elements or values inside a multidimensional array in PHP.

Which is faster foreach or for loop in PHP?

PHP in TeluguThe 'foreach' is slow in comparison to the 'for' loop. The foreach copies the array over which the iteration needs to be performed. For improved performance, the concept of references needs to be used.

What is foreach () in PHP?

What is foreach in PHP? The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.


2 Answers

to achieve just that result you could do

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

but that only works for two arrays

like image 166
Will Avatar answered Sep 20 '22 08:09

Will


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]; } 
like image 45
codaddict Avatar answered Sep 20 '22 08:09

codaddict