Last Updated: February 25, 2016
·
519
· brickattack

Group a collection by X

Say, for example, you're working on a Drupal template where you want to make a grouped slider for a collection of images. Here's a helpful PHP snippet. Pardon the pseudo code.

foreach( $images as $index => $image) :
    $i = $index +1;

    // close container
    if( $i !== 1 && $i % 3 === 1) echo '</div>';

    // open container
    if( $i % 3 === 0) echo '<div>';

    // display image
    echo '<img src="' . $image->url . '" />';
endforeach;

// always close container 
echo '</div>';

This is much easier in Ruby, where there is a method provided by the Array class. http://apidock.com/rails/Array/in_groups_of

%w{ foo bar baz fizz buzz }.in_groups_of(3, false)
#> ['foo','bar','baz']
#> ['fizz','buzz']