I am coding a PHP foreach loop. I am using the following code to ensure that only 3 items are grouped into a .slide div container.
<?php
$count = 0;
foreach ($listing as $item):?>
<div class='slide>
<div class='item'>Item</div>
<?php if ($count++ % 3 == 1 ): ?>
</div>
<div class="slide">
<?php endif; ?>
<?php endforeach ?>
I need to always have 3 items per group. What is the best way to add items from the start of the array to fill up the remaining items?
EDIT:
An example of the markup I need is:
<div class='slide'>
<div class='item'>Item 1</div>
<div class='item'>Item 2</div>
<div class='item'>Item 3</div>
</div>
<div class='slide'>
<div class='item'>Item 4</div>
<div class='item'>Item 1</div>
<div class='item'>Item 2</div>
</div>
So if there is not 3 items per .slide the array starts again to fill it up.
One simple solution is to append 1 or 2 items (if required) to the
$listingvariable before the loop.The
array_slicecall returns an array containing items from0to3 - (size of array) mod 3(either 1 or 2). Thearray_mergefunction then adds these 1 or 2 items to the original$listingarray. The complete code (with some other minor improvements/fixes) is below:Depending on your data, you might need to add special checks for the case where the original
$listinghas 0 or 1 items. Also, probably a good idea not to modify the original array and instead use a copy to append items to and use in the foreach loop.