limiting number of times a loop runs in php
I have a foreach loop that i need to limit to the first 10 items开发者_高级运维 then break out of it.
How would i do that here?
foreach ($butters->users->user as $user) {
$id = $user->id;
$name = $user->screen_name;
$profimg = $user->profile_image_url;
echo "things";
}
Would appreciate a detailed explanation as well.
If you want to use foreach, you can add an additional variable to control the number of iterations. For example:
$i=0;
foreach ($butters->users->user as $user) {
if($i==10) break;
$id = $user->id;
$name = $user->screen_name;
$profimg = $user->profile_image_url;
echo "things";
$i++;
}
You can also use the LimitIterator.
e.g.
$users = new ArrayIterator(range(1, 100)); // 100 test records
foreach(new LimitIterator($users, 0, 10) as $u) {
echo $u, "\n";
}
You could simply iterate over array_slice($butters->users->user, 0, 10)
(the first 10 elements).
Use a loop counter and break
when you want to exit.
$i = 0;
foreach ($butters->users->user as $user) {
$id = $user->id;
$name = $user->screen_name;
$profimg = $user->profile_image_url;
echo "things";
if (++$i >= 10) {
break;
}
}
On the 10th iteration the loop will exit at the end.
There are several variations of this and one thing you need to be choose is whether you want to execute the outer loop condition or not. Consider:
foreach (read_from_db() as $row) {
...
}
If you exit at the top of that loop you will have read 11 rows. If you exit at the bottom it'll be 10. In both cases the loop body has executed 10 times but executing that extra function might be what you want or it might not.
If you're sure about wanting to keep the foreach
loop, add a counter:
$count = 0;
foreach ($butters->users->user as $user) {
$id = $user->id;
$name = $user->screen_name;
$profimg = $user->profile_image_url;
echo "things";
$count++;
if ($count == 10)
break;
}
so each time your loop executes, the counter is incremented and when it reaches 10, the loop is broken out of.
Alternatively you may be able to rework the foreach
loop to be a for
loop, if possible.
you can start a counter before your foreach block and check against it in the loop and break if the counter is 10 like so,
$count = 1;
foreach ($butters->users->user as $user) {
if($count == 10)
break;
$id = $user->id;
$name = $user->screen_name;
$profimg = $user->profile_image_url;
echo "things";
$count++;
}
I really like VolkerK's answer, but I don't understand why he is creating a new iterator when most likely you will have an existing array. Just want to share the way I ended up doing it.
$arrayobject = new ArrayObject($existingArray);
$iterator = $arrayobject->getIterator();
foreach(new LimitIterator($iterator, 0, 10) as $key => $value) {
// do something
}
精彩评论