182 of 410 menu

The array_walk_recursive Function

The array_walk_recursive function applies a given function to all elements of a multidimensional array. It returns true on success or false in case of an error. The first parameter of the function is the array, and the second is the callback.

Two parameters are passed to the callback. The first parameter is the value of the array element, and the second is the key.

The array passed to the function itself is not changed. But this can be achieved by passing the element by reference.

Syntax

array_walk_recursive(array|object &$array, callable $callback, mixed $arg = null): bool

Example

Let's iterate through a multidimensional array and output its keys and elements:

<?php $arr = [ 'a' => 1, 'b' => 2, 'c' => [ 'd' => 3, 'e' => 4, ], ]; array_walk_recursive($arr, function($elem, $key) { echo $key . ' ' . $elem . '<br>'; }); ?>

Code execution result:

'a 1' 'b 2' 'd 3' 'e 4'

Example

Let's iterate through the array and square its elements:

<?php $arr = [ 'a' => 1, 'b' => 2, 'c' => [ 'd' => 3, 'e' => 4, ], ]; array_walk_recursive($arr, function(&$elem, $key) { $elem = $elem ** 2; }); var_dump($arr); ?>

Code execution result:

[ 'a' => 1, 'b' => 4, 'c' => [ 'd' => 9, 'e' => 16, ], ];

See Also

  • the array_walk function,
    which calls a function for array elements
  • the array_map function,
    which applies a function to array elements
  • the array_filter function,
    which filters an array
  • the array_reduce function,
    which reduces an array
byenru