46

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

tarnfeld
  • 24,994
  • 39
  • 109
  • 145

5 Answers5

101

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++) {
}
reko_t
  • 53,784
  • 10
  • 85
  • 77
43

You can either use

break;

or

foreach() if ($tmp++ < 2) {
}

(the second solution is even worse)

Valentin Golev
  • 9,823
  • 9
  • 58
  • 80
25

you should use the break statement

usually it's use this way

$i = 0;
foreach($data as $key => $row){
    if(++$i > 2) break;
}

on the same fashion the continue statement exists if you need to skip some items.

RageZ
  • 25,976
  • 11
  • 66
  • 76
10

In PHP 5.5+, you can do

function limit($iterable, $limit) {
    foreach ($iterable as $key => $value) {
        if (!$limit--) break;
        yield $key => $value;
    }
}

foreach (limit($arr, 10) as $key => $value) {
    // do stuff
}

Generators rock.

Tgr
  • 26,444
  • 11
  • 80
  • 113
7

this is best solution for me :)

$i=0;
foreach() if ($i < yourlimitnumber) {

$i +=1;
}
tcgumus
  • 319
  • 3
  • 8