Dejavu Dejavu - 1 month ago 9
PHP Question

PHP adding different images for every 5 items in a loop

I have several articals I am storing in my database and I have 5 different images I want to show in a foreach loop.
Basically I want to show image2 in every second, seventh, twelfth and so on...

<div id="1">
image1
</div>
<div id="2">
image2
</div>
<div id="3">
image3
</div>
<div id="4">
image4
</div>
<div id="5">
image5
</div>
<div id="6">
image1
</div>
<div id="7">
image2
</div>


Something like :

if ($i == 2 || $i == 7 || $i == 12 || $i == 17 || $i == 22 || $i == 27 )....

Answer

Another options would be to use array_chunk.

http://php.net/manual/en/function.array-chunk.php

Assuming your articles are stored as $articles you could do something like:

$chunks = array_chunk($articles, 5);

foreach ($chunks as $chunk) {

    foreach ($chunk as $key => $article) {

        ?>

        <div>
            Use Image <?php echo $key + 1 ?>
        </div>

        <?php

    }

}

Hope this helps!

Comments