0
0
PhpHow-ToBeginner · 3 min read

How to Use array_walk in PHP: Syntax and Examples

Use 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.
php
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
<?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);
?>
Output
a => Apple b => Banana c => Cherry Array ( [a] => Apple fruit [b] => Banana fruit [c] => Cherry fruit )
⚠️

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
<?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);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 ) Array ( [0] => 2 [1] => 4 [2] => 6 )
📊

Quick Reference

ParameterDescription
arrayThe array to be processed, passed by reference
callbackFunction called for each element, receives value and key
userdataOptional extra data passed to callback

Key Takeaways

Use array_walk to apply a callback to each array element by reference.
Pass the value parameter by reference in the callback to modify array elements.
array_walk modifies the original array; it does not return a new one.
You can pass extra data to the callback using the optional userdata parameter.
Remember array_walk is best for side effects or in-place changes, not for creating new arrays.