joware joware - 24 days ago 9
PHP Question

Fastest way to generate array of given strings specified time in PHP?

We have for example four color names and want to add them to array which will have 9 items. Here is a simple form of the array I want:

$colors = array
(
"blue",
"blue",
"green",
"green",
"red",
"red",
"brown",
"brown",
"brown"
}


But I want to only give a variable and array of colors to get the final array just like this:

$const = array {
"blue",
"green",
"red"
};

$len = 9;


One way to implement this function is to use for loop with some basic calculation but it takes too long in some situations. For example if we want to create such array with 150 inputs and 999 items. So what is the best (or built-in PHP function) to implement this function?

Answer

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!