Reputation: 1475
How can I use array_map to transform an array of variable names into an array of the values of those names? For example:
$arg_array = array('foo', 'bar');
$foo = "asdf";
$bar = "qwer";
print_r(array_map(function($a) {return ${$a};}, $arg_array)); //doesn't work
var_dump(${$arg_array[0]}); //works
Seems like it should be straightforward, but the array_map
function returns Undefined variable: foo
and Undefined variable: bar
, then shows an array of ''
.
Upvotes: 1
Views: 265
Reputation: 13725
I think this is a scoping issue.
Adding a global ${$a}
will help:
print_r(array_map(function($a) {global ${$a};return ${$a};}, $arg_array)); //doesn't
At least if the outer block is the global namespace...
Otherwise this kind of creating names of variables dynamically is not a good sign... This cases are generally convertible to arrays, and the life is much easier with arrays.
Upvotes: 2