PHP Manual
Prev |  | Next

# array_walk

array_walk -- Apply a user function to every member of an array.

## Description

`int array_walk`(array arr, string func, mixed userdata);

Applies the function named by `func` to each element of `arr`. `func` will be passed array value as the first parameter and array key as the second parameter. If `userdata` is supplied, it will be passed as the third parameter to the user function.

If `func` requires more than two or three arguments, depending on `userdata`, a warning will be generated each time array_walk() calls `func`. These warnings may be suppressed by prepending the '@' sign to the array_walk() call, or by using error_reporting().

> Note: If `func` needs to be working with the actual values of the array, specify that the first parameter of `func` should be passed by reference. Then any changes made to those elements will be made in the array itself.

> Note: Passing the key and userdata to `func` was added in 4.0.

> In PHP 4 reset() needs to be called as necessary since array_walk() does not reset the array by default.

Example 1. array_walk() example
      1
      2 $fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
      3
      4 function test_alter (&$item1, $key, $prefix) {
      5    $item1 = "$prefix: $item1";
      6 }
      7
      8 function test_print ($item2, $key) {
      9    echo "$key. $item2<br>\n";
     10 }
     11
     12 array_walk ($fruits, 'test_print');
     13 reset ($fruits);
     14 array_walk ($fruits, 'test_alter', 'fruit');
     15 reset ($fruits);
     16 array_walk ($fruits, 'test_print');
     17

See also each() and list().

Prev | Home | Next
array_values | Up | arsort