将颜色数组插入foreach循环中

$legend = array();
$color[] = ('000000', 'ff0000', 'fasd3f');
    foreach ($stats as $row) {

        if ($row->countofmsg > 0) {

            array_push($legend, "<div class='legend_label'><div class='color-block' style='background:#".$color.";'></div>".ucwords($row->msg)."<div class='legend_count'>$row->count</div></div><div class='clear'></div>");

        }

    }

Here is my code, what I would like to do is set an array of colors $color[], and then inside the foreach loop array, call the first color in the array and then call the second and third and so forth with each thing the foreach spits out. And then repeat at the beginning of the colors array when it reaches the last color in the array.

Would kick out something like:

(color1) msg - count
(color2) msg - count
(color3) msg - count
etc..

Please let me know if there is a duplicate question, I tried researching for it.

This assumes that your $stats array is integer indexed

$legend = array();
$color[] = ('000000', 'ff0000', 'fasd3f');
$colorCount = count($color);
foreach ($stats as $k => $row) {
    if ($row->countofmsg > 0) {
            $legend[] = "<div class='legend_label'><div class='color-block' style='background:#".$color[ ($k % $colorCount) ].";'></div>".ucwords($row->msg)."<div class='legend_count'>$row->count</div></div><div class='clear'></div>";
    }
}
$legend = array();
$color[] = ('000000', 'ff0000', 'fasd3f');
$colorSize = count($color);

foreach ($stats as $row) {
    if ($row->countofmsg > 0) {
        array_push($legend, "<div class='legend_label'><div class='color-block' style='background:#".$color[(3 % $colorSize)].";'></div>".ucwords($row->msg)."<div class='legend_count'>$row->count</div></div><div class='clear'></div>");
    }
}

Edited by @watcher advise but I know the right answer(s) were posted much before.

Use modulo as explained here: https://stackoverflow.com/a/7237074/496735

Except in your case do %3 instead of %2

$color = $colors[$i % 3]; // where $i is the current row