Add to Favorites

Walking the array

There are times that you want to apply some filtering or modifications to all items in an array, but you don't want to build a new array and wan't to keep the array intact. The array_walk php function can be used to accomplish this. The array_walk function takes the following arguments.

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

The array to work on, a function name to run on each item of an array, and an optional argument for additional parameters to supply to your callback function.

Here is an example:

$arr = array(
'item 1',
'item 2 ',
'item 3'
);

function trim_arr(&$arr_item ,$key) {
$arr_item = trim($arr_item);
}

array_walk($arr,'trim_arr');

The above example will trim whitespace off the front and back of each string in the array.

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up