The array_walk() and array_walk_recursive() functions allow you to apply a user-defined function to each element of an array. These functions are useful for modifying array elements in place or recursively modifying elements in multidimensional arrays.
Both functions accept an array and a callback function. The callback receives each value (by reference) so that changes affect the original array.
// Convert all fruit names to uppercase using array_walk()
<?php
$fruits = array("apple", "banana", "cherry");
array_walk($fruits, function(&$value) {
$value = strtoupper($value);
});
print_r($fruits);
?>
The callback function receives each array value by reference, allowing strtoupper() to directly modify the original array elements.
// Recursively convert nested array values to uppercase
<?php
$fruits = array(
"tropical" => array("mango", "pineapple"),
"berries" => array("strawberry", "blueberry")
);
array_walk_recursive($fruits, function(&$value) {
$value = strtoupper($value);
});
print_r($fruits);
?>
The recursive version automatically walks through every level of the array and applies the callback to all nested values.
// Increase each number by 5 using array_walk()
<?php
$numbers = array(10, 20, 30);
array_walk($numbers, function(&$value) {
$value += 5;
});
print_r($numbers);
?>
This visual flow shows how array_walk() processes each element sequentially.
// Each element passes through the callback function one by one
Array → [Callback Function] → Modified Original Array
[v1, v2, v3] → f(&$v) → [V1, V2, V3]
array_walk() for single-level arrays.array_walk_recursive() for nested arrays.array_walk().