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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
shorif2000
  • 2,582
  • 12
  • 65
  • 137
  • 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 – Emz Sep 21 '16 at 08:17

1 Answers1

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);
Tadas Paplauskas
  • 1,863
  • 11
  • 15