Amit Dhamu

Software Engineer

Use An Array Recursively

Let's say that you have a dynamic list with items coming in from a database. For each item in the list, you want the background colour to be different.

Firstly, create an array of colours.

$colours = [

Then, to loop through each item and assign the next colour in the array AND THEN start the colours from the beginning again if there are more items than colours:

$i = 0;

// Lets assume my items are stored in an array called $items
foreach ($items as $item) {
    echo "<div style='background:" . $colours[($i % count($colours))] . ";'>";
    echo $item;
    echo "</div>";

 colours / random / arrays / php

Save Canvas as PNGAutoload Class

Show Comments

Made with by Amit Dhamu.
© MMXX. All rights reserved.