tags:

views:

3225

answers:

4

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

+5  A: 

You can either use

break;

or

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

(the second solution is even worse)

valya
+6  A: 

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
the last one would be very slow and bad. use 1 or 2 instead.
thephpdeveloper
A: 

Use a for loop

Why would you try to use a foreach loop if you only want the first two elements? You are trying to make something work for something it wasn't originally intended to do.

Better to just stick with a simple for loop rather then trying complicate matters and having to use ugly workarounds.

James
for isn't necessarily any simpler if he's dealing with an associative array; you'd have to do something like: $keys = array_keys($arr); for ($i = 0; $i < min(2, count($arr)); $i++) { $key = $keys[$i]; $val = $arr[$key]; /* do stuff */ }In my opinion foreach is cleaner, but if it's not an associative array then definitely use for.
reko_t
Yep, keyed arrays make `foreach` a far better alternative.
ceejayoz
A: 

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
should be > 2, otherwise it will break before abnything fun happens :)
phidah
tks @phidah I have edited ^^
RageZ