PHP array_walk() Function
In this chapter you will learn:
- Definition for PHP array_walk() Function
- Note for PHP array_walk() Function
- Syntax for PHP array_walk() Function
- Parameter for PHP array_walk() Function
- Example - Map an array with user defined function
- Example - With a parameter
- Example - Change an array element's value. (using the &$value)
Definition
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.
Note
To walk an array inside an array, use the array_walk_recursive() function.
Syntax
PHP array_walk() Function has the following syntax.
array_walk(array,myfunction,parameter...)
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 |
Example 1
Map an array with user defined function
<?php//from j av a 2 s . com
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.
Example 2
With a parameter:
<?php/*from j a v a2 s . c om*/
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.
Example 3
Change an array element's value. (using the &$value)
<?php/*from ja v a 2 s . c o m*/
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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_walk_recursive() Function
- Syntax for PHP array_walk_recursive() Function
- Parameter for PHP array_walk_recursive() Function
- Example - Run user defined function on array element
Home » PHP Tutorial » PHP Array Functions