array_walk_recursive(): traversing multi-dimensional array
PHP 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
Author & Instructor at
plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com