The array walk function helps you change or use each item in a list one by one.
Array walk function in PHP
<?php function callback_function(&$value, $key, $user_data) { // Change or use $value here } array_walk(array &$array, callable $callback, mixed $user_data = null): bool; ?>
The callback function receives the value by reference, so you can change it directly.
The callback also gets the key and optional extra data you pass.
<?php function add_five(&$value, $key) { $value += 5; } $numbers = [1, 2, 3]; array_walk($numbers, 'add_five'); print_r($numbers);
<?php function greet($value, $key) { echo "Hello, $value!\n"; } $names = ['Anna', 'Bob']; array_walk($names, 'greet');
<?php function to_uppercase(&$value, $key) { $value = strtoupper($value); } $words = ['apple', 'banana']; array_walk($words, 'to_uppercase'); print_r($words);
<?php function add_suffix(&$value, $key, $suffix) { $value .= $suffix; } $fruits = ['apple', 'banana']; array_walk($fruits, 'add_suffix', ' fruit'); print_r($fruits);
This program adds an exclamation mark to each word in the list and shows the list before and after.
<?php function add_exclamation(&$value, $key) { $value .= '!'; } $words = ['hello', 'world', 'php']; // Before change print_r($words); // Change each word array_walk($words, 'add_exclamation'); // After change print_r($words); ?>
Time complexity is O(n) because it visits each item once.
Space complexity is O(1) since it changes items in place.
Common mistake: forgetting to pass the value by reference in the callback, so changes don't apply.
Use array_walk when you want to change or use each item without creating a new list. Use array_map if you want a new list instead.
array_walk lets you run a function on each item in a list.
You can change items directly by passing them by reference.
You can also pass extra data to the function if needed.