Recently whilst working on the reskin of a mammoth web application written in PHP, I encountered a scenario where I needed to wrap elements within a div every four iterations.
The task is simple enough and if you’ve worked with WordPress before especially, you’ll know the aged-old approach is to use a counter and then the modulus operator.
While the modulus and counter approach does work, it is hacky, complicated and messy. You’re probably wondering if there is a better way and there this.
Say hello to “array_chunk”
The array_chunk method in PHP is a very underrated function. It does what it says on the tin, it splits arrays into chunks. If an array has 40 items in it and we want to split it up into smaller chunks of say 10, we would have four arrays within an array adding up to 40.
Surprisingly, when I tell people about my use of array_chunk (which I’ve been using for a very long time) they are surprised and impressed. Most developers out there are still using the modulus operator like it is their only choice, this is why I have decided to write a blog post to make more people aware of array_chunk.
Wrap every four elements in a DIV (or any number)
<?php
foreach (array_chunk($items, 4, TRUE) AS $chunks) {
echo '<div class="wrapper">';
foreach ($chunks AS $item) {
echo '<div class="item">';
echo '<h2>'.$item->name.'</h2>';
echo '</div>';
}
echo '</div>';
}
?>
This solution worked best for me. Thanks!
Thank you, this was a very clear and helpful explanation!