Getting two items at a time from a loop

Hi,

I am building a timeline, having pulled all the timeline items through the controller, I can create a loop easily enough to get all of the items. But what I want to do (example below) is get all timeline items then loop through two of them at a time. The reason is that I want to display them a specific way.

I am not sure how to do this, clearly I need to get all the items which I can do, but then I need to then process two items at a time until the loop is out of items. Does that make sense? Can anyone suggest a way to do this?

<?php foreach($items as $item): ?>
    <?= Display 1st item this way ?>
    <?= Display 2nd item a different way ?>
<?php endforeach ?>

Thanks for your valuable assistance as always.

Lee

The best way is probably to create chunks of two:

<?php 
$chunks = $items->chunk(2);
foreach ( $chunks as $chunk ) : 
?>
<div class="chunk-wrapper">

  <?php foreach ( $chunk as $item) : ?>
    <?php if ( $item->indexOf($items) === 0 ) : ?>
        <div class="first-item">This is the first item</div>
    <?php else: ?>
        <div class="second-item">This is the second item</div>
    <?php endif ;?>
</div>
<?php endforeach ?>
1 Like

Another way:

<?php $i=0; foreach($items as $item): $i++; ?>
    <?php if ($i%2): ?>
        <?= Display 1st item this way ?>
    <?php else: ?>
        <?= Display 2nd item a different way ?>
    <?php endif; ?>
<?php endforeach ?>
1 Like

Thanks Bruno, that makes complete sense and works perfectly, thank you very much.