Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Abdulsalam's avatar

Copy array multiple times

Hello everyone, I would like to do something like this:

$main = []
$number = 5;
[ 'value' => '', 'type' => 'col'] * $number

I want the result to be something like this:

$main = [
  0 => [ 'value' => '', 'type' => 'col'],
  1 => [ 'value' => '', 'type' => 'col'],
  2 => [ 'value' => '', 'type' => 'col'],
  3 => [ 'value' => '', 'type' => 'col'],
  4 => [ 'value' => '', 'type' => 'col'],
]

The size of new $main array would be depending on the variable $number, which changes.

Is there a way to do this without pushing to the $main array in a loop?

0 likes
7 replies
Sinnbeck's avatar

Something like

$main = [];
$number = 5;
foreach(range(1, $number) as $i) {
    $main[] = [ 'value' => '', 'type' => 'col'];
}
Abdulsalam's avatar

@Sinnbeck thank you for responding. This work great and I've implemented it this way, but I'm wondering if there is a way to get the same result without using a foreach or for loop. Maybe some function in PHP, which multiply array by a number, which I don't know about.

tykus's avatar

@Abdulsalam it it not native PHP, but for Laravel's Collections it is trivial as I showed below (there is still a foreach but it is abstracted away using map)

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Abdulsalam How about this then

$number = 5;
$main = array_fill(0, $number, [ 'value' => '', 'type' => 'col']);
1 like
tykus's avatar

A one-liner (if you like):

collect()->times(5)->map(fn () => ['value' => '', 'type' => 'col'])->all()

Please or to participate in this conversation.