tags:

views:

193

answers:

6

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.

+1  A: 

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.

cletus
typo there, should be `($i++ > 10)`
Tatu Ulmanen
This will break the `foreach` loop with the first iteration.
Gumbo
+4  A: 

If you want to use foreach, you can add additionbal variable to control iterations:

$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++;  
} 
Alex
It should be if($i==10) and not =10.
Jimmie Lin
You forgot a `=` in `$i=10`.
Gumbo
Thank you for correction.
Alex
+1  A: 

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.

richsage
A: 

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++;
} 
Pragati Sureka
+2  A: 

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";
}
VolkerK
A: 

You could simply iterate over array_slice($butters->users->user, 0, 10) (the first 10 elements).

Ciarán Walsh