Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping a div around every third item in a foreach loop PHP [closed]

//set the array
$info = array(
'andy' => 'blue',
'andrew' => 'black',
'mark' => 'green',
'jane' => 'orange',
'simon' => 'red',
'joan' => 'pink',
'sue' => 'yellow',
'alan' => 'black') 


$i = 1;

foreach($info as $key => $val){

    <div class="holder">
        <div class="name">
            <?php echo $Name ?> 
        </div>
        <div class="colour">
            <?php echo $colour ?> 
        </div>
    </div>
} 

This dispalys each "holder" class... but what I am wanting to do is wrap a container around the "holder" class and have 3 "holder" in each "container". eg:

<div class="container">
    <div class="holder">
            <div class="name">
                <?php echo $Name ?> 
            </div>
            <div class="colour">
                <?php echo $colour ?> 
            </div>
        </div>
    <div class="holder">
            <div class="name">
                <?php echo $Name ?> 
            </div>
            <div class="colour">
                <?php echo $colour ?> 
            </div>
        </div>
    <div class="holder">
            <div class="name">
                <?php echo $Name ?> 
            </div>
            <div class="colour">
                <?php echo $colour ?> 
            </div>
        </div>
</div>

I cant find out how to either get the index of the associative array, or how to break a foreach loop once %3 == 0.

Any suggestions would be awesome!

-Ved

like image 396
Ved Avatar asked Dec 01 '22 05:12

Ved


1 Answers

You need to have a separate counter variable:

$i = 0;
foreach($info as $key => $val){
  if($i%3 == 0) {
    echo $i > 0 ? "</div>" : ""; // close div if it's not the first
    echo "<div class='container'>";
  }
  ?>
    <div class="holder">
        <div class="name">
            <?php echo $Name ?> 
        </div>
        <div class="colour">
            <?php echo $colour ?> 
        </div>
    </div>
<?php
$i++;
}
?>
</div> <!-- close last container div -->
like image 132
chiborg Avatar answered Dec 04 '22 12:12

chiborg