Using PHP: Array_chunking (or making your rows clean and counter less)

Too often, we have to write views/templates which require counters external to the key value in the foreach() statement because we need to add things like:

<div class="row"></div> 

 

An Example might look something like this:

<?php 	$limit = 3; 	$i = 1; ?> <?php foreach($posts as $k=>$post):?> 	<?php if($i == 1):?> 		<div class=”row”> 	<?php endif;?>  	<div><?php echo $post->title?></div>  	<?php if($i == $limit):?> 		</div> 	<?php endif;?> <?php $i++;?> <?php endforeach;?> 

Its a hassle to add two IF statements at the top and bottom within each foreach() statement to detect every third item added. But there is a solution! Check out below where we use Array_chunk()!

<?php foreach(array_chunk($posts, 3) as $posts_row):?> 	<div class=”row”> 	<?php foreach($posts_row as $post):?> 	<div><?php echo $post->title?></div> 	<?php endforeach;?> 	</div> <?php endforeach;?> 

Where credit is due: I found out about this technique here.