Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Your Email:
Webmaster Blog

PHP array_walk(): Run an array through a function

by Akash Mehta


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

<?php
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().

Usage
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:

<?php
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).

Syntax
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.



Tags: ,


Related Posts
» Debugging PHP code using debug_backtrace
» Intelligent Geocoding using PHP and Yahoo Web Services
» Iterating PHP objects, and readable code too!
» Unexpected return value from Facebook FQL.query
» PHP Script execution time and maximum workaround
 


Leave a Reply

Ask A Question
characters left.