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

2
  • Did you try array_push() instead? I've used that and had a lot of success with it. Commented Jun 9, 2011 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. Commented Jun 9, 2011 at 17:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This one answers the question I had, though I also really like mario's answer below... thanks for help from both of you!
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.

1 Comment

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.

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.