Search code examples
phparraysrepeat

Duplicate each string in a flat array N times


I would like to repeat each value 3 times and put it in the correct order. In place of each original element 3 copies of itself should take its place.

Given the following one-dimensional array of strings:

$chars = ["a", "b", "c"];

So result would be:

$duplicatedChars = ["a", "a", "a", "b", "b", "b", "c", "c", "c"];

I have tried working with str_repeat(), but this does not create separate strings.

This attempt doesn't create enough elements, it only repeats the string within each element.

$result = [];
foreach ($chars as $char) {
    $result[] = str_repeat($char, 3);
}

Solution

  • str_repeat creates a single string, not an array.

    Use array_fill() to create an array with N copies of a value. Then append the array to the result.

    foreach ($chars as $char) {
        $result = array_merge($result, array_fill(0, 3, $char));
    }