Cleaning up your templates with array_chunk Posted on January 23rd, 2014
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.