0

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`.

10
  • array_fill (or array_fill_keys) might help here. Commented Nov 21, 2013 at 16:07
  • 1
    $newItems = array_fill(0, $x, $items);` Commented Nov 21, 2013 at 16:08
  • why do you need copies of this array? Commented Nov 21, 2013 at 16:08
  • 1
    The second param can be anything (except perhaps a resource, I've never tried with a resource) - scalar, array, object, even nested arrays of objects or functions Commented Nov 21, 2013 at 16:11
  • 1
    Whoops, never mind. I was looking at the doc for array_fill_keys, which @RocketHazmat initially mentioned. I see that array_fill does take three params. Commented Nov 21, 2013 at 16:13

1 Answer 1

2

Using array_fill()

$newItems = array_fill(0, $x, $items);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.