php wrap every N elements

Wrap every 3 elements with div.row:

<?php
$index = 1;
 
foreach( $sub_pages as $sub_page ) {
 
	if ($index % 3 == 1 || $index == 1) { // beginning of the row or first
		echo '<div class="row">';
	}
 
	echo '<div class="col-sm-4">';
 
	echo $sub_page->post_title;
	echo $sub_page->post_excerpt;
 
	echo '</div><!-- .col -->';
 
	if ($index % 3 == 0 || $index == count($sub_pages)) { // end of the row or last
		echo '</div><!-- .row -->';
	}
 
	$index++;
}
?>

Wrap every 5 elements using array_chunk():

$chunks = array_chunk($original, 5);
foreach ($chunks as $each_chunk) {
        // echo out as unordered list
}

Leave a Reply

Your email address will not be published. Required fields are marked *