The array_walk() function runs a user-defined function on each array element.
The array's keys and values are parameters in the function.
We can change the value in the user-defined function by specifying the first parameter as a reference: &$value.
To walk an array inside an array, use the array_walk_recursive() function.
PHP array_walk() Function has the following syntax.
array_walk(array,myfunction,parameter...)
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to walk on |
myfunction | Required. | The name of the user-defined function |
parameter,... | Optional. | A parameter to the user-defined function. You can assign one parameter to the function, or as many as you like |
Map an array with user defined function
<?php
function myfunction($value,$key){
echo "The key $key has the value $value<br>";
}
$a=array("a"=>"A","b"=>"B","c"=>"java2s.com");
array_walk($a,"myfunction");
?>
The code above generates the following result.
With a parameter:
<?php
function myfunction($value,$key,$p){
echo "$key $p $value ==";
}
$a=array("a"=>"A","b"=>"B","c"=>"java2s.com");
array_walk($a,"myfunction","has the value");
?>
The code above generates the following result.
Change an array element's value. (using the &$value)
<?php
function myfunction(&$value,$key){
$value=" added";
}
$a=array("a"=>"A","b"=>"B","c"=>"java2s.com");
array_walk($a,"myfunction");
print_r($a);
?>
The code above generates the following result.