22

Basically I need to create this array (given x = 3)

array('?','?','?');

I could do

for ($i = 0; $i < 3; $i++)
    $arr[] = '?';

But it's not so elegant. Is there any other way?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

29

Use array_fill( start_index, num, value ):

$arr = array_fill(0, 3, '?');
Paul
  • 139,544
  • 27
  • 275
  • 264
0

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'));
BadHorsie
  • 14,135
  • 30
  • 117
  • 191
  • The asker already knows how to push within a loop. The advice on appending more elements to an already populated array is moreso topically related to the content found @ [Duplicate each string in a flat array N times](https://stackoverflow.com/q/68909837/2943403) – mickmackusa May 23 '23 at 21:06