get the first 6 items

I have a small php code. This code get the title’s of the blog items. But i have a question about this code.

How can I make it. That pick-up of last 6 titles?

Read More
<ul class="blog-list">
    <?php foreach ($siblings as $sibling) : ?>
    <li><a href="<?php echo get_permalink($sibling->ID); ?>" data-nav-position="fade"><?php echo get_the_title($sibling->ID); ?></a></li>
    <?php endforeach; ?>
</ul>

Thanks for help

Related posts

Leave a Reply

3 comments

  1. Easiest option with not many changes in your.

    <ul class="blog-list">
        <?php $i = 0; ?>
        <?php foreach ($siblings as $sibling) : ?>
        <li><a href="<?php echo get_permalink($sibling->ID); ?>" data-nav-position="fade"><?php echo get_the_title($sibling->ID); ?></a></li>
        <?php if(++$i>=6) break; ?>
        <?php endforeach; ?>
    </ul>
    
  2. If you take some of elements of array do not use foreach (see the word each?).

    Use for loop instead

    for($i = 0; $i < 6; ++$i){
      $sibling = $siblings[$i];
    

    to get first 6 or

    for($i = count($siblings); $i > count($siblings) - 6; --$i){
      $sibling = $siblings[$i];
    

    to get last six (in reverse order)

    EDIT

    This won’t work if array keys are not integers or have some empty ranges in it. You may then use array_slice() as suggested in other answer or array_pop() six times.