Search code examples
phpforeachpaginationlimit

How to skip the first instance in a foreach loop and limit to 8?


I was wondering if anyone could give me a hand with this... Basically I am trying to modernize the news system of my site but I can't seem to limit the amount of posts showing in the foreach loop that is on my blog part of the site. I need to skip the first instance as it is already promoted at the top of the page. I've tried various google searches but im getting results for C++ Perl and python, what is really irritating. I just need a simple PHP solution. I'll pop my code below and see if anyone can help. Thanks for any help in-advance. And please remember to leave your responses as an answer so I can mark them up if they helped ;)

<div class="view22 full" style="margin-top:0;">
    <h3>Recent News and Announcements</h3>
    <?php foreach ($articles as $article) { 
?>
        <div class="ah7_ clearfix">
            <p class="date"><?php echo date('F j', $article['article_timestamp']); ?>, <?php echo date('Y', $article['article_timestamp']); ?></p>
            <h3><a href="<?php echo $url.'/newsroom/'.$article['article_id']; ?>"><?php echo $article['article_title']; ?></a></h3>
        </div>
    <?php 
    }
?>
</div>

Solution

  • I assume that the $articles array has keys starting with 0. How about modifying the loop like this:

    foreach ($articles as $key => $article) 
    

    and checking if $key is 0 at the beginning?

    if($key == 0)
       continue;
    

    If the array keys are different: Create a new variable $i, set it to 0 and increase the value by 1 in every foreach loop iteration.

    $i = 0;
    foreach ($articles as  $article) {
       $i++;
       if($i == 1)
          continue;
       elseif($i > 8)
          break;
    
       //the other code goes here
    }
    

    In case it is based on a SQL query, using "limit" might help to reduce load!