Change Order in a Foreach Loop

Iā€™m creating a website for a publication and they would like to take some articles from their blog and feature it on their homepage. I have a feature toggle installed on an article blueprint and then created a snippet I attach to the home.php that looks for if the toggle is on and limited it to breaking after it finds three. The only issue is that it starts from the articles from oldest to most recent. Is there any easy way to change this? Can I start the foreach loop from the most recent?

Here is my code:

  $blog = page('archive')->children();
  $counter = 0;
  foreach($blog as $articles) : ?>

  <?php if($articles->feature() == 'yes') {

      <article class="article index" >
        <header class="article-header">
          <div class="ftimg">
          <a href="<?= $articles->url() ?>">
            <?php echo $articles->featureimage()->toFile() ?>
          <h2 class="article-title">
            <a href="<?= $articles->url() ?>"><?= $articles->title()->html() ?></a>

          <h3 class="article-subtitle"> <?= $articles->subtitle()->html() ?></h3>
          <div class="article-details">
            <h4 class="article-author"> <?= $articles->author()->html() ?> ā€”</h4>
            <p class="article-date"āˆ‚><?= $articles->date('F jS, Y') ?></p>
  <?php if($counter == 3) break; } else {


  <?php endforeach ?>

That is a lot easier:

$featuredArticles = page('archive')->children()->sortBy('date', 'desc')->filterBy('feature', '==', 'yes')->limit(3);
foreach($featuredArticles as $article): ?>
<!-- your code here -->
<?php endforeach ?>

(note that I changed your variable naming scheme, I find a plural for a single article in the foreach loop highly irritating)

1 Like

Yeah, this is way way cleaner. Working like a charm! Thank you!