3

I am trying to use array map dynamically, the column in the array may change so I don't want to specify it using string but want to use a variable to specify it, it does not work. Tried all the following combinations, it returns null.

$column = 'MANAGER_GROUP';
array_map(function($el){ return $el['"'.$column.'"']; }, $dbData);
array_map(function($el){ return $el["$column"]; }, $dbData);
array_map(function($el){ return $el[$column]; }, $dbData);

//this works though
array_map(function($el){ return $el["MANGER_GROUP"]; }, $dbData);
1
  • 1
    You have to use the keyword "use" in php To access variables outside your Closure function which in your case the Callback Function.. see the answer Below by Tadas Commented Sep 21, 2016 at 8:17

1 Answer 1

6

Anonymous function has it's own scope, it does not have access to parent scope automatically. You have to explicitly specify a variable to be passed to anonymous function context.

$column = 'MANAGER_GROUP';
array_map(function($el) use ($column) { 
    return $el[$column];
}, $dbData);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.