fr3d
fr3d

Reputation: 685

PHP loop need to create new div every 5 elements

I've got a forech loop that displays 50 logos. But what I need is another loop that creates a new div(.autogrid_wrapper .cte .block) every 5 images.

    <div class="autogrid_wrapper cte block">
        <div class="inner">
            <?php foreach($this->entries as $entry): ?>
                <figure class="image_container">
                    <img src="<?php echo $entry->field('logo')->generate(); ?>" title="<?php echo $entry->field('name')->value(); ?>" alt="<?php echo $entry->field('name')->value(); ?>" >
                </figure>
            <?php endforeach; ?>
        </div>
</div>

I hope you guys can help me.

Upvotes: 0

Views: 308

Answers (1)

Sougata Bose
Sougata Bose

Reputation: 31749

A simple counter could help -

<div class="autogrid_wrapper cte block">
    <div class="inner">
        <?php 
        $i = $j = $k = 0;
        foreach($this->entries as $entry): 
        $i++;
        $class = '';
        if($j === 0) {
            $class = 'first';
        }
        $j++;
        $html = '';
        if($i % 5 === 0) {
            $k++;
            $j = ($i - (5 * $k));
            $class = 'last';
            $html = "</div></div>
                 <div class='autogrid_wrapper cte block'><div class='inner'>";
        } 
        ?>
            <figure class="image_container <?php echo $class; ?>">
                <img src="<?php echo $entry->field('logo')->generate(); ?>" title="<?php echo $entry->field('name')->value(); ?>" alt="<?php echo $entry->field('name')->value(); ?>" >
            </figure>
        <?php 
        echo $html;
        endforeach; 
        ?>
    </div>
</div>

Upvotes: 3

Related Questions