Using array_chunk()
By using array_chunk()
you can generate a multi-dimensional array, with 5 elements in each.
$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
$carsGrouped = array_chunk($cars, 5);
foreach($carsGrouped as $carGroup){
echo "<div class='col-lg-2'><ul>";
foreach($carGroup as $car) {
echo "<li>{$car}</li>";
}
echo "</ul></div>";
}
https://eval.in/652005
Using Modulus
By using the modulus operator (%
) you can check if your counter ($i
) is divisible by 5
, and if it is, then end the current <div>
and start a new <div class='col-lg-2'>
.
$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
echo '<div class=\'col-lg-2\'>
<ul>';
$i = 0;
foreach($cars as $car){
++$i;
echo '<li>'. $car .'</li>';
if($i>1 AND ($i%5)===0 AND $i<count($cars)) { //We've printed 5 $car, we need to do another "group".
echo '</ul>
</div>
<div class=\'col-lg-2\'>
<ul>';
}
}
echo '</ul>
</div>';
https://eval.in/651965