How to Use array_walk in PHP: Syntax and Examples
array_walk in PHP to apply a callback function to each element of an array. The callback receives the element value and key, allowing you to modify or process each item directly.Syntax
The array_walk function takes an array and a callback function as its main arguments. The callback function should accept at least two parameters: the value and the key of each array element. Optionally, you can pass a third argument to array_walk which will be sent to the callback.
- array: The input array to process.
- callback: A function that takes the value and key, and optionally a user parameter.
- userdata (optional): Extra data passed to the callback.
bool array_walk(array &$array, callable $callback, mixed $userdata = null)Example
This example shows how to use array_walk to print each element with its key, and then modify the array values by appending a string.
<?php $fruits = ['a' => 'Apple', 'b' => 'Banana', 'c' => 'Cherry']; // Print each element array_walk($fruits, function($value, $key) { echo "$key => $value\n"; }); // Modify each element by appending text array_walk($fruits, function(&$value, $key) { $value .= ' fruit'; }); // Print modified array print_r($fruits); ?>
Common Pitfalls
One common mistake is forgetting to pass the array by reference to array_walk, which means changes inside the callback won't affect the original array. Also, the callback must accept the value parameter by reference if you want to modify the array elements.
Another pitfall is confusing array_walk with array_map: array_walk modifies the original array in place, while array_map returns a new array.
<?php // Wrong: value not passed by reference, so no change $numbers = [1, 2, 3]; array_walk($numbers, function($value, $key) { $value *= 2; // This won't change original array }); print_r($numbers); // Right: value passed by reference to modify array array_walk($numbers, function(&$value, $key) { $value *= 2; }); print_r($numbers); ?>
Quick Reference
| Parameter | Description |
|---|---|
| array | The array to be processed, passed by reference |
| callback | Function called for each element, receives value and key |
| userdata | Optional extra data passed to callback |