///PHP array_walk(): Run an array through a function

PHP array_walk(): Run an array through a function

If you’ve been developing with PHP for a while, you’ve probably come across this situation in the past:

foreach ($somearray as &$element) {
    $element = some_function($element);

It’s a common sight: taking an array and running (well, walking) its elements through a particular function. Luckily, PHP provides a simple yet powerful function to overcome this: array_walk().

Using array walk is simple. It takes two arguments, an array of data and a callback function to pass the array to. It examines the array and calls the callback function with each element of the array, allowing you to run the entire array through the function without extracting the array yourself. Consider this:

function some_function(&$element, $key) {
    return $element + 1;

// This:
foreach ($somearray as $key=>&$element) $element = some_function($element, $key);

// becomes this:
array_walk($somearray, "some_function");

It’s cleaner, faster and more effective. It also gives your callback function more information than you might usually provide. The callback parameter can be any : “function_name”, array(‘Class_name’, ‘method_name’) or even array($object, ‘method_name’) (where $object can be $this as needed).

The syntax is very simple:

array_walk (array &$array, callback $callback[, mixed $userdata]);

The first parameter is the array that you want to run through the function. The second is the callback – for a function, class method or object method. The third allows you to pass a third parameter to the callback function from within the current context. This can be anything at all, and along with the array element and its key/index, will be passed directly to the function without modification.

For more details, see array_walk() in the PHP manual.

2008-04-22T03:41:28+00:00 April 22nd, 2008|PHP|0 Comments

About the Author:

Leave A Comment