1

I have a bunch of arrays, which are stored in different variables like $required, $reserved, etc...

I would like to allow (inside a function) an array of options to be passed (like $options = array('required', 'reserved')), and that array would then be used to define which arrays to merge together and return at the end of the function.

So, I have this code in part of the function, that should grab all the options and merge the arrays, using variable variables to get the arrays from the strings passed in the options array):

$array = array();

foreach ($options as $key) {
  $array_to_merge = ${$key};
  array_merge($array, $array_to_merge);
}

return $array;

However, when I return the $array, it shows 0 items. If I print_r($array_to_merge);, I actually get the entire array as I should.

Does array_merge() simply not work with variable variables, or am I missing something here...?

geerlingguy
  • 4,682
  • 8
  • 56
  • 92
  • Did you try `array_push()` instead? I've used that and had a lot of success with it. – Dave Kiss Jun 09 '11 at 17:23
  • Variable Variables are best avoided in scripts, because they can create a hard to debug confusion. If something like this is related, you're usually better of defining them as an array with their names as indexes. – Wrikken Jun 09 '11 at 17:30

2 Answers2

4

array_merge returns the merged array, you're not assigning that return value to anything and thus it is being lost.

$array = array_merge($array, $array_to_merge);

should fix your problem.

Austin Fitzpatrick
  • 7,243
  • 3
  • 25
  • 22
  • This one answers the question I had, though I also really like mario's answer below... thanks for help from both of you! – geerlingguy Jun 09 '11 at 17:55
1

If I read it right you can also simplify your code (replaces the loop) to just:

 $array = call_user_func_array("array_merge", compact($options));

compact replaces the variable variable lookup and gets the list of arrays. And in effect there is only one array_merge call necessary.

mario
  • 144,265
  • 20
  • 237
  • 291
  • Wow, that's awesome! Never used/seen compact() before, and it does almost exactly what I need... unfortunately, I have a multidimensional array here, so I don't know if compact is best in this instance. – geerlingguy Jun 09 '11 at 17:54