PHP array_walk vs array_map: Key Differences
This article explains the key differences between the
array_walk() and array_map() functions in PHP.
While both functions are used to apply a callback function to array
elements, they differ significantly in their return values, how they
handle array keys, and whether they modify the original array in place.
Understanding these distinctions will help you write cleaner and more
efficient PHP code.
1. Return Value and In-Place Modification
The most fundamental difference lies in how these functions handle the data they process and what they return.
array_walk(): Operates “in-place” on the original array. It modifies the array directly by passing the value as a reference (&$value) in the callback. It returns a boolean value (trueon success orfalseon failure).array_map(): Does not alter the original array. Instead, it creates and returns a brand-new array containing the modified elements.
2. Callback Parameters and Keys
The two functions pass different arguments to their respective callback functions.
array_walk(): Passes both the value and the key of each element to the callback function. It also allows you to pass an optional third parameter to the callback for custom user data.array_map(): Passes only the value of the array elements to the callback function. By default, it does not have access to the array keys.
3. Handling Multiple Arrays
array_walk(): Can only operate on a single array at a time.array_map(): Can accept and process multiple arrays simultaneously. If multiple arrays are passed, the callback function receives elements from each array in parallel.
Code Comparison
Using array_walk()
$fruits = ['a' => 'apple', 'b' => 'banana'];
// Modifies the original array in-place
array_walk($fruits, function(&$value, $key) {
$value = strtoupper($value);
});
print_r($fruits);
// Output: Array ( [a] => APPLE [b] => BANANA )Using array_map()
$fruits = ['a' => 'apple', 'b' => 'banana'];
// Returns a new array, leaving the original unchanged
$upper_fruits = array_map(function($value) {
return strtoupper($value);
}, $fruits);
print_r($upper_fruits);
// Output: Array ( [a] => APPLE [b] => BANANA )Summary: When to Use Which?
Use array_walk() when you want to
modify an existing array in place without creating a copy, or when you
need access to the array keys during iteration.
Use array_map() when you want to
generate a new array based on the values of one or more existing arrays,
keeping the original data intact.