Search code examples
phparraysfor-loopclone

php - create x number of copies of array


I'm looking more for guidance here than actual code. I already know how I can do this; just wondering if there's a better way.

I have a variable $x, which is an integer. Can be any number. I have an array, $items.

$items = Array('qty'=>3, 'name'=>'pizza');

I want to create $x copies of $items, each of which will become a 'subarray' of a new array called $newItems.

I know I can do a for loop sort of like this:

for($i=1;$1<=$x,$i++) {
   $newItems[$x] = $items;
}

Is there a better way to do this? (The example is simplified so if it were just like this, it wouldn't be a problem to do the loop. But in reality, I have a parent array called $menu that has multiple $menu_items nodes, so I'm already doing a foreach($menu_items as $id->$items), which the above loop would then need to be nested in. It would be nice if there was some function I don't know about where I could just say "make $x copies of this array`.


Solution

  • Using array_fill()

    $newItems = array_fill(0, $x, $items);