Wrap items by a div inside foreach loop

Wrap items by a div inside foreach loop is a very common practice in coding. But some are getting this bit complicated but it is not. We can achieve this in two ways. Both methods are easy.

01. Using if else  and remainder value

Example: Assuming I have an array of images. And  I need to wrap every three images with a div. You can use your own value. Just for the example I am using three.

Then your code should be like this.

$counter = 1;
foreach( $images as $image )
{
    if ($counter%3 == 1)
    {  
         echo '<div>';
    }
    echo '<img src=" . $image['url'] . " alt=" . $image['alt'] . " />';
    if ($counter%3 == 0)
    {
        echo '</div>';
    }
    $counter++;
}

If you have more HTML to add or you’re bit unfamiliar with writing HTML codes inside PHP echo, no worries you can break the loop and add your HTML code (you preferred way) then you can end the foreach loop.

02. Using array chunk PHP

Next method we can achieve this is breaking down the array and use it. Lets use and see above example here.

foreach (array_chunk($images, 3, true) as $gallery) {
    echo '<div>';
    foreach($gallery as $image) {
         echo '<img src=" . $image['url'] . " alt=" . $image['alt'] . " />';
    }
    echo '</div>';
}

Using array chunk you are required to breaking down the array and make another array for your use. Using that you can loop through another foreach. This is foreach inside another foreach method. Nesting foreach loop you need to use here. If bit complicated go through again and you’ll realize nothing much here.

foreach (array_chunk($images, 3, true) as $gallery)

What does this code is doing here. It is taking $images array and three items from it. Then it is creating another array named $gallery. Now there is another array for you named $gallery and it contains only three images. So, here I have defined open

and close

, before loop through my second foreach. Because that is what wanted. You can define ids and classes inside the

. That is just HTML and I am not going to explain on that.

Within the second foreach you just need to print the . Because you have done all other stuff outside. So, we are done now. Hope you understood the array_chunk and its stuff.

Hope you will get to know more from this.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *