Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Limit foreach() statement? [closed]

Tags:

foreach

php

limit

How can i limit a foreach() statement? Say i only want it to run the first 2 'eaches' or something?

like image 605
tarnfeld Avatar asked Nov 01 '09 11:11

tarnfeld


People also ask

How do you end a foreach loop?

To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.

Can I use break in foreach PHP?

break ends execution of the current for , foreach , while , do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1 , only the immediate enclosing structure is broken out of.


1 Answers

There are many ways, one is to use a counter:

$i = 0; foreach ($arr as $k => $v) {     /* Do stuff */     if (++$i == 2) break; } 

Other way would be to slice the first 2 elements, this isn't as efficient though:

foreach (array_slice($arr, 0, 2) as $k => $v) {     /* Do stuff */ } 

You could also do something like this (basically the same as the first foreach, but with for):

for ($i = 0, reset($arr); list($k,$v) = each($arr) && $i < 2; $i++) { } 
like image 89
reko_t Avatar answered Sep 27 '22 22:09

reko_t