array_walk_recursive(): traversing multi-dimensional array

Current PHP usage

array_walk_recursive() applies a callback to every non-array value inside a nested array. It descends through nested arrays automatically.

$data = ['a' => 1, 'group' => ['b' => 2]];
array_walk_recursive($data, function (&$value) {
    $value *= 10;
});
print_r($data);

The callback receives leaf values; nested arrays themselves are not passed to it as leaf values.

The array_walk_recursive() function in PHP applies a user-defined callback function to each element of an array, including elements in nested arrays. It's useful for traversing multi-dimensional arrays.

Syntax

array_walk_recursive(array $array, callable $callback, mixed $userdata = null): bool

Example 1: Simple Array

function display($value, $key) {
    echo "$key: $value <BR>";
}
$array = ['a' => 1, 'b' => 2];
array_walk_recursive($array, 'display');
a: 1 
b: 2 

Example 2: Nested Array

function display($value, $key) {
    echo "$key: $value <BR>";
}
$array = [
    'a' => 1, 
    'b' => ['c' => 2, 'd' => 3]
];
array_walk_recursive($array, 'display');
a: 1 
c: 2 
d: 3 

Example 3: Using Userdata

$array = [
    'a' => 1, 
    'b' => ['c' => 2, 'd' => 3]
];

$prefix = "Prefix";

array_walk_recursive($array, function($value, $key) use ($prefix) {
    echo "$prefix $key: $value <br>";
});
Prefix a: 1 
Prefix c: 2 
Prefix d: 3 

Difference between array_walk_recursive() and array_walk():

array_walk():
Operates only on the top-level elements of an array.
Does not iterate over nested arrays.

array_walk_recursive(): Operates on all elements, including nested arrays.
Recursively applies the callback to each element.

Use array_walk() for flat arrays and array_walk_recursive() for multi-dimensional arrays where nested elements need to be processed.

Conclusion

The array_walk_recursive() function is essential when processing nested arrays, as it allows the application of a callback to each element, regardless of the array’s depth.
To check the variable is array or not array_walk()
Array REFERENCE


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer