-1

$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");

I need to get 2 col-lg-2 for each 5 rows inside this structure:

$car

how can it done ?

for the first 5 rows i made this:

<div class='col-lg-2'><ul>
<?php $i=0;
foreach($cars as $car){
  echo "<li>$car</li>";
  $i++;
  if($i==5) break;
} ?>
</ul></div>

how can I echo the next 5 ?

Mina Magdy
  • 63
  • 8

3 Answers3

2

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

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
0

Using the modulus division operator as suggested, here is a possible solution;

$cars       = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "s", "ee");
$iCount     = 0;
$sOutput    = '';

foreach($cars as $sCarName){

    if ($iCount % 5 == 0)
       $sOutput .= ($iCount > 1 ? "</ul>\n</div>\n" : '')."<div class='col-lg-2'>\n<ul>\n";

    $sOutput .= "<li>".$sCarName."</li>\n";

    $iCount ++;
}

if( $iCount > 1 ){
    $sOutput .= "</ul>\n</div>";  
} 

echo $sOutput;

N.B. its not valid html to have a div as a child of an UL, explained here

Community
  • 1
  • 1
atoms
  • 2,993
  • 2
  • 22
  • 43
-1
<?php
$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
?>
<div class='col-lg-2'><ul>
<?php 
$i=0;
foreach($cars as $car_name){
echo "<li>$car_name</li>";
$i++;
if($i==5): 
    echo "</ul></div><div class='col-lg-2'><ul>";
    $i = 0;
endif;
} 
?>
</ul></div>
Jefferson Costa
  • 188
  • 1
  • 9