Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_walk_recursive() function

Reference for PHP array_walk_recursive(): apply a callback to every leaf value of a nested array, modify values by reference, and pass extra arguments.

array_walk_recursive() is the nested version of array_walk(). It visits every leaf value in a multidimensional array, however deep, and calls your callback on each one. Sub-arrays themselves are not passed to the callback; PHP descends into them instead.

If the callback takes its first parameter by reference, it can change the array in place. This makes it handy for trimming every string in decoded JSON or escaping all values before output.

PHP
<?php
$data = ["a" => [1, 2], "b" => 3];
array_walk_recursive($data, function (&$v) { $v *= 10; });
// ["a" => [10, 20], "b" => 30]

Try it

PHP Changing every leaf value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Keys, extra arguments and totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_walk_recursive(array|object &$array, callable $callback, mixed $arg = UNKNOWN): true
Name Description
$array The array (or object) to walk. Passed by reference.
$callback Called as callback(&$value, $key, $arg). Take $value by reference to modify the array.
$arg Optional extra value passed to the callback as its third argument.

Return value: always true. (Older versions declared bool.)

Usage notes

  • Only leaves are visited. For ["a" => [1, 2]] the callback sees 1 and 2 with keys 0 and 1, never the array under "a".
  • Keys are those of the innermost array. You do not get the full path. If you need the path, write your own recursive function.
  • Change values, not structure. Modifying keys or adding elements to the array being walked leads to confusing results.
  • Pass by reference (&$value) to modify. Without it the callback can only read.
  • Returns nothing useful. Unlike array_map(), it does not build a new array, so it is cheaper for in-place changes.
  • Objects: public properties are walked as if they were array elements.
  • Typical uses: sanitizing input, applying trim() to all strings, summing numbers in a tree, finding values.