PHP array_walk_recursive with closure

Using PHP’s new support for closures/anonymous functions is particularly helpful with array functions that otherwise would require a separate callback function. One recent example where I used this is to grab a simple array of user_id=value from a nested array. (Values shown below are somewhat simplified.)

It does seem to be true that this strategy is most useful when the callback function you define is used on multiple arrays and has some level of complexity. One advantage of this is that it does use a little less memory by only keeping the global callback function registered while it’s being used.

If it wasn’t a recursive array, you could simply use array_walk, or even a foreach loop. My guess is the real-world performance would be about the same in most cases, and while the example below is simplified, I would like to see some cases where a closure or anonymous function is a dramatic improvement over previous methods.

$people_ids = array();
$callback = function ($value, $key) use (& $people_ids) {
    if ($key == 'people_id') {
        $people_ids[] = $value;
array_walk_recursive($people_list, $callback);
echo '<pre>$people_ids: '; print_r($people_ids); echo '</pre>';

see below for a before and after example of this.

view example

$people_list =array();
$people_list[0] = array(
	'people_info' => array('people_id' => 1),
	'first_name' => 'FirstName',
	'last_name' => 'LastName',
	'job_title' => 'Designer',
	'department_id' => 2
$people_list[1] = array(
	'people_info' => array('people_id' => 3),
	'first_name' => 'FirstTwo',
	'last_name' => 'LastTwo',
	'job_title' => 'JobTitle',
	'department_id' => 1
// result:
$people_ids Array
    [0] => 1
    [1] => 3

also see here and for more about array_walk vs array_map, see here

One Response to “ “PHP array_walk_recursive with closure”

  1. Igor says:

    Thanks, this example helped me a lot!

Leave a Reply