Master PHP’s array_walk(): From Basics to Advanced Use Cases
Learn how PHP’s powerful array_walk() function lets you iterate over arrays and apply custom callbacks, with clear examples ranging from simple value transformations to advanced techniques like passing userdata, using reference parameters, and integrating class methods for real-world development scenarios.
array_walk()is a powerful PHP function that allows developers to traverse an array and execute a custom operation on each element.
Its syntax is simple: array_walk($array, $callback, $userdata); Where $array is the array to traverse, $callback is the function to execute, and $userdata is an optional parameter that can pass additional data to the callback.
Below is a basic example that squares each number in an array and prints the key and the squared value.
$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 will be:
The square of 0 is 1
The square of 1 is 4
The square of 2 is 9
The square of 3 is 16
The square of 4 is 25Advanced usage includes passing extra data via $userdata. For example, to 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";Note that to modify $userdata inside the callback, it must be passed by reference; otherwise its value will not be retained.
You can also use array_walk() with class methods. For instance:
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() can be applied to tasks such as 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.
