Apply a user-defined function to each element of an array.
<?php function myfunction($value,$key) { echo “The key $key has the value $value<br>”; } $a=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”); array_walk($a,“myfunction”); ?> |
The array_walk()
function applies a user-defined function to each element of an array, with the array’s keys and values as parameters.
Note: You can modify an array element’s value in the user-defined function by using a reference for the first parameter: &$value
(see Example 2).
Tip: For handling multidimensional arrays (arrays within arrays), use the array_walk_recursive()
function.
array_walk(array, myfunction, parameter…) |
Parameter |
Description |
array |
Required. Specifying an array |
myfunction |
Required. The name of the user-defined function |
parameter,… |
Optional. Specifies a parameter to the user-defined function. You can assign one parameter to the function, or as many as you like |
Return Value: |
Returns |
PHP Version: |
4+ |
<?php function myfunction($value,$key,$p) { echo “$key $p $value<br>”; } $a=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”); array_walk($a,“myfunction”,“has the value”); ?> |
Modify an array element’s value (note the use of &$value
).
<?php function myfunction(&$value,$key) { $value=“yellow”; } $a=array(“a”=>“red”,“b”=>“green”,“c”=>“blue”); array_walk($a,“myfunction”); print_r($a); ?> |