treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Reverse PHP Increment

  • I'm trying to display a number next to each article with the following code in Kirby.

          <?php 
              $count = 0;
              foreach($page->children()->visible()->flip() as $article):
              $count++
          ?>
    
          <article>
            <span="numeral"><?php echo $count; ?></span>
            <h1><a href="<?php echo html($article->url()) ?>"><?php echo html($article->title()) ?></a></h1>
            <time pubdate="pubdate"><?php echo $article->date('n/j/Y') ?></time>
          </article>
          <?php endforeach ?>
    

    However, it's outputting like this
    1 Latest Article
    2 Older Article

    I need it to output like this
    2 Latest Article
    1 Older Article

  • Maybe set the counter to the highest number, and count down.

    I took a peek at the Kirby API cheat sheet I came up with this.

    <?php 
              $count = $page->count();
              foreach($page->children()->visible()->flip() as $article):
              $count--;
          ?>
    

    http://getkirby.com/content/02-docs/kirby-cheatsheet.pdf

  • <?php 
        $articles = $page->children()->visible()->flip();
        $count = $articles->count();
        foreach($articles as $article):
      ?>
          <article>
            <span="numeral"><?php echo $count; ?></span>
            <h1><a href="<?php echo html($article->url()) ?>"><?php echo html($article->title()) ?></a></h1>
          </article>
    <?php
          $count--;
        endforeach
      ?>
    
  • @hotpink I had to change your code as it was counting all the pages, I think (it started from 16).

      $count = $page->children()->count();
    

    This echos out 0 for the first article where I need it to echo out 1.

  • @hotpink is correct, but the page count will end in zero. Subtract at the end of the loop to end with one.

  • Nice @benwalker. Thank you!

    Edit: Also, thank you @hotpink

  • Actually, scrap that. My code is the one to use :-)

    ... I think

  • @BenWalker Your code works perfectly.

  • wow, code parser is terrible on this site. nvm my help http://pastebin.com/h7aCGq0d