Home » Php » PHP – Adding divs to a foreach loop every 4 times

PHP – Adding divs to a foreach loop every 4 times

Posted by: admin April 23, 2020 Leave a comment

Questions:

I need a little help with a foreach loop.

Basically what i need to do is wrap a div around the output of the data every 4 loops.

I have the following loop:

foreach( $users_kicks as $kicks ) {
    echo $kicks->brand;
}

For every 4 times it echos that out i want to wrap it in a so at the end it will look like so:

<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>
<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>
<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>

and so on.

Cheers

How to&Answers:
$count = 1;
foreach( $users_kicks as $kicks ) 
{
    if ($count%4 == 1)
    {  
         echo "<div>";
    }
    echo $kicks->brand;
    if ($count%4 == 0)
    {
        echo "</div>";
    }
    $count++;
}
if ($count%4 != 1) echo "</div>"; //This is to ensure there is no open div if the number of elements in user_kicks is not a multiple of 4

Answer:

This answer is very late – but in case people see it – this is a cleaner solution, no messy counters and if statements:

foreach (array_chunk($users_kicks, 4, true) as $array) {
    echo '<div>';
    foreach($array as $kicks) {
         echo $kicks->brand;
    }
    echo '</div>';
}

You can read about array_chunk on php.net

Answer:

Try % modulus operator.

$i=1;
//div begins
foreach( $users_kicks as $kicks ) {
   if($i % 4 ==0)
    {
      //div ends
      //div begins
    }
    echo $kicks->brand;
   $i++;
}
//div ends

Answer:

you can also use array_chunk which cut array by blocks

$blocks = array_chunk($users_kicks, 4);
foreach ($blocks as $block) {
    echo '<div>';
    foreach ($block as $kicks) {
        echo $kicks->brand;
    }
    echo '</div>';
}

Answer:

A little modification to AVD’s answer to make sure there is no empty DIV if array is empty or it’s count is factor of 4…

if($lastRec=count($user_kicks)){
  echo '<div>';
  $i=1;
  foreach( $users_kicks as $kicks ) {
    if( ($i % 4 == 0) && ($i<$lastRec) ) echo '</div><div>';
    echo $kicks->brand;
    $i++;
  }
  echo '</div>';
}

Answer:

<?php
$item_count=1;
$items_block=3;
?>
<div class="wrapper">
    <?php if(!empty($list)){ ?>

        <div class="item_block">
            <?php foreach ($list as $val){ ?>
                <div>Item</div>

                <?php 
                if($item_count % $items_block==0){ ?>
                    </div>
                    <div class="item_block">
                <?php 
                } 
                $item_count++;
                ?>

            <?php endforeach; ?>
        </div>
    <?php } ?>
</div>