spacer
Web Development Blog
 Developer Newsletter

Webmaster Blogs
Content & Blogging
Design
Photoshop
General
JavaScript
PHP
PHP Functions
Web
WordPress
Website Promotion

Blog Archives


Developer Tutorials
AJAX
ASP
CGI & Perl
CSS
Flash
HTML
Illustrator
Java
JavaScript
Linux
MySQL
PHP
Photoshop
Python
Wireless
XML
Miscellaneous

Scripts Directory
AJAX Scripts
ASP Scripts
ASP.NET Scripts
CGI & Perl Scripts
Flash Scripts
Java Scripts
JavaScript Scripts
PHP Scripts
Python Scripts
Remotely Hosted Scripts
Tools & Utilities Scripts
XML Scripts

Web Hosting Directory
ASP.NET
Budget
Dedicated Servers
Ecommerce
Linux
Resellers
Shared
Small Business
Windows

Webmaster Blog

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:

<?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





About the NetVisits, Inc Network | Write For Us | Advertise
Copyright ©2007 NetVisits, Inc Network. All Rights Reserved. Privacy Policy.
Visit other NetVisits, Inc. sites: