PHP array_walk() function
Example
Apply a user-defined function to each element in the 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"); ?>
Definition and Usage
The array_walk() function applies a user-defined function to each element in the array. In the function, the array key name and key value are parameters.
Note:You can change the value of the array element by specifying the first parameter of the user-defined function as a reference: &$value (see example 2).
Tip:To operate deeper arrays (an array containing another array), please use array_walk_recursive() Function.
Syntax
array_walk(array,myfunction,userdata...)
Parameters | Description |
---|---|
array | Required. Specifies the array. |
myfunction | Required. The name of the user-defined function. |
userdata,... | Optional. Specifies the parameters for the user-defined function. You can pass any number of parameters to this function. |
Description
The array_walk() function applies a callback function to each element in the array. If successful, it returns TRUE, otherwise FALSE.
In typical cases myfunction accepts two parameters.array The value of the parameter is used as the first, and the key name as the second. If optional parameters are provided userdata It will be passed as the third parameter to the callback function.
if myfunction the function requires more parameters than those provided, then each array_walk() call myfunction will always generate an E_WARNING level error. These warnings can be suppressed by adding PHP's error operator @ before the array_walk() call or by using error_reporting().
Note:If the callback function needs to directly act on the values in the array, you can specify the first parameter of the callback function as a reference: &$value. (See example 3)
Note:will append the key name and userdata passed to myfunction is a new feature added in PHP 4.0.
Technical Details
Return Value: | Returns TRUE if successful, otherwise returns FALSE. |
PHP Version: | 4+ |
More Examples
Example 1
Set a parameter:
<?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"); ?>
Example 2
Change the value of an array element (note &$value):
<?php function myfunction(&$value,$key) { $value="yellow"; } $a=array("a"=>"red","b"=>"green","c"=>"blue"); array_walk($a,"myfunction"); print_r($a); ?>