Well, I'm not sure if I fully understand your question. But based on your input ($const and $len) & output ($colors) above, I may get your idea. Here's a function to generate an array of colors:
function generateColorArray(array $colors, $length) {
$totalColors = count($colors);
if ($totalColors === 0 || $length <= 0) {
return [];
}
$colorArray = [];
$colorBlockSize = (int) floor($length / $totalColors);
$totalRemainder = $length % $totalColors;
if ($colorBlockSize === 0) {
return array_slice($colors, 0, $length);
}
foreach ($colors as $color) {
$colorArray = array_merge($colorArray, array_fill(0, $colorBlockSize, $color));
}
if ($totalRemainder > 0) {
$colorArray = array_merge($colorArray, array_fill(0, $totalRemainder, $colors[$totalColors - 1]));
}
return $colorArray;
}
Let's say you want to generate an array of colors with the length of 9 from the following list of colors:
$colors = ['blue', 'green', 'red', 'brown'];
You may use the above generateColorArray() function to generate the array of colors:
$collorArray = generateColorArray($colors, 9);
// The result would be:
Array
(
[0] => blue
[1] => blue
[2] => green
[3] => green
[4] => red
[5] => red
[6] => brown
[7] => brown
[8] => brown
)
What happen when the given $length parameter is less than the total number of $colors? The above function will also handle this situation:
$collorArray = generateColorArray($colors, 3);
// The result would be:
Array
(
[0] => blue
[1] => green
[2] => red
)
And when you pass an empty array of $colors or $length value equal or less than zero, the function will simply return an empty array.
Hope this help!