Backend Development 5 min read

Using PHP's array_walk() Function: Syntax, Examples, and Advanced Usage

This article explains PHP's powerful array_walk() function, detailing its syntax, parameter roles, basic and advanced examples—including squaring numbers, summing values with userdata, and invoking class methods—while highlighting practical use‑cases for backend development.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_walk() Function: Syntax, Examples, and Advanced Usage

The array_walk() function is a powerful PHP utility that iterates over an array and applies a user‑defined callback to each element.

Its syntax is straightforward: array_walk($array, $callback, $userdata); where $array is the target array, $callback is the function to execute, and $userdata is an optional parameter that can pass additional data to the callback.

Basic usage : to square each number in an array, define a square function and call array_walk() on the numeric array.

$numbers = array(1, 2, 3, 4, 5);
 function square($value, $key) {
     $value = $value * $value;
     echo "The square of $key is $value\n";
 }
 array_walk($numbers, 'square');

This produces output such as "The square of 0 is 1", "The square of 1 is 4", etc., demonstrating that array_walk() passes both the value and its key to the callback.

Advanced usage with $userdata : you can accumulate data across iterations, for example to calculate the sum of all numbers.

$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; otherwise changes will not persist after the function returns.

Using array_walk() with class methods : define a class with a method to filter or process array items, instantiate the class, and pass the method as a callback.

class MyClass {
     public function filter($value, $key) {
         // filtering code here
     }
 }
 $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 log file parsing, field formatting or validation, request parameter filtering, and many other scenarios where a uniform operation must be applied to each element of an array, improving code readability and maintainability.

backend developmentPHPCode Examplecallbackarray_walkuserdata
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.