Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach array get 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.

Something like

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

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

Any ideas?

Marvellous

like image 829
RIK Avatar asked Jul 14 '11 14:07

RIK


3 Answers

Use array_slice():

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

foreach(array_slice($shops,9,9) as $shop){
   // etc.
}
like image 159
AJ. Avatar answered Sep 21 '22 12:09

AJ.


How about

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

and

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

??

like image 28
Mark Avatar answered Sep 22 '22 12:09

Mark


Use a for loop instead?

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

Then you could do another with $i = 10..19. If you must use foreach then have a counter you increment and break; or use array_slice as others have suggested.

like image 25
David Amey Avatar answered Sep 20 '22 12:09

David Amey