array_walk_recursive(): traversing multi-dimensional array

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 
"; } $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 
"; });
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
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



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-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer