Contact Us

How to render fixed length rows of items

Posted on 9/3/09 by Felix Geisendörfer

Hey folks,

if you find yourself in a situation where you need to write a template that splits up a list of items in multiple rows with each row having a fixed amount of items, here is a simple solution:

<div class="items">
  <?php while ($items): ?>
    <div class="row">
      <?php for ($i = 0; ($item = array_shift($items)) && $i < 4; $i++): ?>
        <div class="item">
          <?php echo $item['Item']['title']; ?>
      <?php endfor; ?>
  <?php endwhile; ?>

This will put 4 items in each row and a smile on your face for not having to write very ugly code to achieve the same : ).

-- Felix Geisendörfer aka the_undefined


You can skip to the end and add a comment.

Neil Crookes said on Mar 09, 2009:

And also: and 2 nested foreach statements

Matt Campbell said on Mar 10, 2009:

I recently had to do this for something myself. Only I fill by column instead of by row. Pasting code into the comment didn't work so I made a post here.">'>here.

Mauro said on Mar 18, 2009:

until today I used the if($i%4==0) statement but this is really nice. Thanks!

Eric Lawless  said on Apr 03, 2009:

Neil Crookes' idea seems as if it would be cleaner, and has the benefit of being non-destructive.

elvy said on Apr 12, 2009:

Hi Felix - thanks for the great posts -

I think that in the for loop, you should flip the order of $i less than 4 condition and the array_shift operation with each other.

Otherwise it will devour an array item each loop, i.e. when $i less than 4 fails, the array has already been shifted - right?


This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.