Search code examples
phploopsforeachlimit

limit results in foreach loop


The code below I have works fine but I wanted to check with you, the experts, to make sure I was using best practices.

I want to limit the loop results to 16. Does the code below seem like the best method?

Thanks, Jeffrey

foreach ($flickr_set['items'] as $id => $photos) {
$ctr=0;  
         foreach ($photos as $photo) {
if($ctr>=16) break; else $ctr++; /* limits results to 16 */  
        echo '<a href="' . $photo['large'] . '" title="' . $photo['title'] . '" rel="flickr-set" ><img src="' . $photo['thumb'] . '" /></a>';
    }
}

Solution

  • Your solution is fine, if you want a more structured solution which might be also more understandable, you can use array_slice:

    foreach ($flickr_set['items'] as $id => $photos) {
             foreach (array_slice($photos, 0, 16) as $photo) { 
            echo '<a href="' . $photo['large'] . '" title="' . $photo['title'] . '" rel="flickr-set" ><img src="' . $photo['thumb'] . '" /></a>';
        }
    }