Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limiting number of times a loop runs in php

Tags:

foreach

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.

like image 835
mrpatg Avatar asked Jan 04 '10 08:01

mrpatg


5 Answers

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++;  
} 
like image 177
Alex Avatar answered Oct 18 '22 02:10

Alex


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";
}
like image 30
VolkerK Avatar answered Oct 18 '22 00:10

VolkerK


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

like image 36
Ciarán Walsh Avatar answered Oct 18 '22 02:10

Ciarán Walsh


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.

like image 36
cletus Avatar answered Oct 18 '22 02:10

cletus


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.

like image 1
richsage Avatar answered Oct 18 '22 01:10

richsage