blainelang
8/29/2013 - 7:37 PM

Using an anonymous function with array_walk and passing in a variable so that it's in scope for the function to use.

Using an anonymous function with array_walk and passing in a variable so that it's in scope for the function to use.

/* Objective: Loop over an array of Drupal user objects and build a string of email addresses for the $to variable.
 * At first there was an issue because the variable $to_email_array was not being accessible to the anonymous function
 * and then I saw answer2 to a similar question:  
 *   > http://stackoverflow.com/questions/11420520/php-variables-in-anonymous-functions 
*/

$to_email_array = array();
array_walk($users_group, function(&$user, &$uid) use (&$to_email_array) {
  $to_email_array[] = $user->mail;
});
$to = implode(',', $to_email_array);