Loop list in batches using Twig (or plain PHP)

Recently I had to loop through a series of elements in a WordPress template (thanks Timber), which happened to be using Bootstrap.

If you ever used Bootstrap, you are familiar with the following markup:

The problem here is very common. You have to:

  • Loop every 3/4/n items.
  • Insert a separator or whatever every 3/4/n items.

You can achieve this with modulo (divisibleby) and checking if the loop index is last and other weird magic. However, Twig introduced the batch filter in version 1.12.3, where you can make this much less cumbersome.

So, adapting the current example and their docs, this is how we achieve a clean loop:

Much better, right?

I realized PHP has a built-in function that handles this. It’s called array_chunk which, of course, splits an array into chunks (or batches as I recalled, and the reason why I hadn’t been able to find it on the docs.)

Edit 19 Jul: Added plain PHP version.