Skip to content

Instantly share code, notes, and snippets.

@itsjavi
Created June 1, 2012 08:40
Show Gist options
  • Select an option

  • Save itsjavi/2850400 to your computer and use it in GitHub Desktop.

Select an option

Save itsjavi/2850400 to your computer and use it in GitHub Desktop.
PHP function for grouping elements in a loop
<?php
/**
* PHP function for grouping elements in a loop
* @param int $times Group max items
* @param array $items
* @param string $html_before Group start html
* @param string $html_after Group close html
* @param string $fn Callable function name that generates the item HTML
* @param int $offset
* @param int $limit
* @return string The generated HTML (all groups)
*/
function group_every($times, $items, $html_before, $html_after, $fn, $offset=0, $limit = null){
$cursor = $cursor2 = $offset;
$last = !empty($limit) ? $limit : count($items);
$last-=1;
$html = "";
while($cursor <= $last){
echo $html_before;
for($i = $cursor; $i < ($cursor + $times); $i++){
$cursor2 = $i;
if($cursor2 > $last) break;
$html .= call_user_func($fn, $i, $items[$i]);
}
$cursor = $cursor2+1;
echo $html_after;
}
return $html;
}
@itsjavi
Copy link
Author

itsjavi commented Jun 1, 2012

Example:

<?php
        echo group_every(4, $images, '<div class="filmstrip-row">', '</div>', 'tpl_filmstrip_row_item');
?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment