Apply a user-defined function to each element in the array:
<?phpfunction 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 in an array. In the function, the key name and key value of the array are parameters.
Note: You can change the value of an array element by specifying the first parameter in the user-defined function as a reference: &$value (see Example 2).
Tip: To operate on deeper arrays (one array within another array), use the array_walk_recursive() function.
array_walk( array,myfunction,parameter... )
parameter | describe |
---|---|
array | Required. Specifies an array. |
myfunction | Required. The name of the user-defined function. |
parameter,... | Optional. Specifies the parameters of a user-defined function. You can set one or more parameters for the function. |
Return value: | Returns TRUE if successful, otherwise returns FALSE. |
---|---|
PHP version: | 4+ |
With one parameter:
<?phpfunction myfunction($value,$key,$p){echo "$key $p $value<br>";}$a=array("a"=>"red","b"=>"green ","c"=>"blue");array_walk($a,"myfunction","has the value");?>Change the value of an array element (note the &$value):
<?phpfunction myfunction(&$value,$key){$value="yellow";}$a=array("a"=>"red","b"=>"green","c"=>" blue");array_walk($a,"myfunction");print_r($a);?>