PHP: Limit foreach() statement?


Question

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

1
32
11/1/2009 11:50:00 AM

Accepted Answer

You can either use

break;

or

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

(the second solution is even worse)

36
11/1/2009 11:52:37 AM

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++) {
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon