PHP foreach array gets first 9 results, then second 9

Using PHP foreach, how would I get only the first 9 results in one foreach and only the second 9 in another.

Sort of

foreach {$ stores [1 - 9] as $ shop) {

foreach {$shops[10 - 18] as $shop) { 

Any ideas?

Wonderful

+6
source share
6 answers

Use array_slice() :

 foreach(array_slice($shops,0,9) as $shop){ // etc. } foreach(array_slice($shops,9,9) as $shop){ // etc. } 
+9
source

Use a for loop instead?

 for (int $i = 0; $i < 9; $i++) { $shop = $shops[$i]; } 

Then you can do something else with $i = 10..19 . If you must use foreach , use the counter you increment and break; or use array_slice as others suggested.

+3
source

What about

 foreach (array_slice($shops, 0, 9) as $shop) { ... } 

and

 foreach (array_slice($shops, 9, 9) as $shop) { ... } 

??

+1
source
 foreach (array_chunk($shops, 9) as $section) { // Do some logic on each section foreach ($section as $shop) { // Do some logic on each shop } } 
+1
source

using array_slice you can split your array into two, then you can do it

 $my_array = array('1','2',...,'18'); $first_array = array_slice($my_array,0,9); $second_array = array_slice($my_array,9,18); 
0
source

Use the for loop instead.

 for ($i = 0; $i < 9; $i++) { $shop = $shops[$i]; } for ($i = 9; $i < 18; $i++) { $shop = $shops[$i]; } 
0
source

Source: https://habr.com/ru/post/892754/


All Articles