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
2009-11-01 11:52:37
+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
2009-11-01 11:55:22
the last one would be very slow and bad. use 1 or 2 instead.
thephpdeveloper
2009-11-01 11:56:26
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
2009-11-01 12:01:43
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
2009-11-01 12:06:10