开发者

PHP - Variable Variables & array_merge() - not working

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 $o开发者_如何学Cptions = 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...?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜