Cleaning up your templates with array_chunk

array_chunk splits an array into a series of arrays of a given size or as the docs say “array_chunk — Split an array into chunks”. This is useful when you want to display an array in multiple columns. Take the following template:

<?php $total = count($posts) ?>

<?php foreach($posts as $k => $post): ?>

    <?php if($k == 0): ?>
        <div class="row">
    <?php elseif ($k % 3 == 0): ?>
        </div><div class="row">
    <?php endif; ?>

    <!-- $post dom here -->

    <?php if($total === $k - 1): ?>
        </div>
    <?php endif; ?>
<?php endforeach; ?>

This code displays posts in a series of rows. Each row contains 3 posts and is wrapped in <div class="row"></div>. The code works, but it’s not the easiest on the eyes. The if else at the top of the loop is confusing. Below we write the same code but using array_chunk instead of index math.

<?php foreach(array_chunk($posts, 3) as $postsInRow): ?>
    <div class="row">
        <?php foreach($postsInRow as $post): ?>
            <!-- $post dom here -->
        <?php endforeach; ?>
    </div>
<?php endforeach; ?>

There are a couple of benefits here. Since we’re using array_chunk the row length, 3, is easy to find and change. We no longer rely on index math, this prevents potential issues when $posts is an associative array. Finally the dom structure inside the loop matches the output structure. There is no longer a closing div tag at the top of our loop.

  • http://dongilbert.net/ Don Gilbert

    Brilliant.

  • http://yuriybabenko.com Yuriy Babenko

    Great idea. I’ve been looking at that function (on and off) for years, never seeing a purpose for it.

  • bencoder

    While array_chunk can be useful in certain situations, you probably shouldn’t be hard coding rows of 3 like this anymore. Modern CSS3 can take care of splitting it for you and hard coding rows of 3 will make it impossible to employ good responsive design techniques.

  • Pingback: PHPDeveloper.org: Community News: Recent posts from PHP Quickfix