d
Amit DhamuSoftware Engineer
 

Use An Array Recursively

1 minute read 00000 views

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 = [
    '#505d6a',
    '#832b67',
    '#612b83',
    '#2b3f83',
    '#2b8367',
    '#0096b6',
    '#1fa400',
    '#ff7e00',
    '#990000',
    '#707d00'
];

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>";
    $i++;
}