What Does array_walk Do?
The array_walk function applies a user-defined callback function to each element in an array. It can also pass the array key as a parameter to the callback.
The array_walk function in PHP is a powerful tool that allows you to apply a custom callback function to each element of an array. But what if you’re unable to use built-in array functions or want to explore how it works internally? This post will show you how to manually implement the behavior of array_walk.
Example:
$input = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
array_walk($input, function (&$value, $key) {
$value = strtoupper($value);
});
// Output: ['a' => 'APPLE', 'b' => 'BANANA', 'c' => 'CHERRY']
Manual Implementation of array_walk in PHP
Here’s how you can replicate this functionality without using the array_walk function.
Example:
function manualArrayWalk(&$array, $callback) {
foreach ($array as $key => &$value) {
$callback($value, $key);
}
}
// Test Case
$input = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
manualArrayWalk($input, function (&$value, $key) {
$value = strtoupper($value);
});
// Output
print_r($input);
Output:
Array
(
[a] => APPLE
[b] => BANANA
[c] => CHERRY
)
How It Works:
- Define the Function:
Create a function named manualArrayWalk that accepts two parameters:- The array (passed by reference).
- A callback function.
- Loop Through the Array:
Use a foreach loop to iterate over the array, passing both the key and value. - Apply the Callback:
Call the callback function for each element, passing the value and key as arguments. The value is passed by reference, allowing modifications. - Test the Function:
Provide an array and a callback function to test its functionality.
Why Avoid Built-in Functions?
- Understanding Core Concepts: By building it yourself, you gain a deeper understanding of PHP’s array handling.
- Customizable Logic: You can tweak the function to suit your specific needs.
Keep Learning 🙂