Push the same element x times onto the array

Use array_fill( start_index, num, value ):

$arr = array_fill(0, 3, '?');

To address the question of how to push the same element a number of times onto an array, it's worth noting that while array_fill() is certainly the most elegant choice for generating a new array, this is the only thing it can do. It cannot actually push elements onto an existing array.

So while a basic loop isn't particularly exciting, it does work well in situations where you have an existing array you want to add to, regardless of whether it's already empty or not.

$arr = ['a', 'a', 'a'];

for ($i = 0; $i < 3; $i++) {
    $arr[] = 'b';
}
print_r($arr);
Array
(
    [0] => a
    [1] => a
    [2] => a
    [3] => b
    [4] => b
    [5] => b
)

To achieve the same thing with array_fill() it requires an additional merge:

$arr = array_merge($arr, array_fill(0, 3, 'b'));

Tags:

Php

Arrays