Master PHP’s array_walk: Transform Arrays with Custom Callbacks
This article explains PHP’s array_walk function, detailing its syntax, basic and advanced usage with code examples, including passing extra userdata, using callbacks, and integrating class methods, while highlighting practical scenarios where array_walk simplifies array processing in backend development.
array_walk() is a powerful PHP function that lets developers iterate over an array and apply a custom operation to each element. array_walk($array, $callback, $userdata); $array is the array to traverse, $callback is the function to execute, and $userdata is an optional parameter that can pass extra data to the callback.
Basic usage example: square each number in an array.
$numbers = array(1, 2, 3, 4, 5);
function square($value, $key) {
$value = $value * $value;
echo "The square of $key is $value
";
}
array_walk($numbers, 'square');The output shows each element’s key and its squared value.
Advanced usage includes passing additional data via $userdata. Example: calculate the sum of all elements.
$sum = 0;
function sum($value, $key, $userdata) {
$sum = $userdata;
$sum += $value;
return $sum;
}
$numbers = array(1, 2, 3, 4, 5);
$sum = array_walk($numbers, 'sum', $sum);
echo "The sum of all numbers is $sum";When modifying $userdata inside the callback, it must be passed by reference to retain changes.
array_walk() can also be used with class methods. Example:
class MyClass {
public function filter($value, $key) {
// filtering code
}
}
$myClass = new MyClass();
$array = array('a','b','c','d','e');
array_walk($array, array($myClass, 'filter'));In real-world development, array_walk() is useful for parsing log files, formatting or validating database fields, filtering request parameters, and many other scenarios, greatly simplifying code and improving readability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
