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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With