Definitions and usage
The Array_walk () function applies a callback function to each element in the array. Returns TRUE if successful, otherwise returns FALSE.
Typically, a function accepts two parameters. the value of the array parameter is the first, and the key name is the second. If an optional parameter userdata is provided, it is passed as the third argument to the callback function.
If a function function requires more arguments than is given, a e_warning error is generated each time Array_walk () invokes the function. These warnings can be suppressed by adding PHP's error operator @ before the Array_walk () call, or by using error_reporting ().
Grammar
Array_walk (Array,function,userdata ...)
Parameters |
Description |
Array |
Necessary. The specified array. |
function |
Necessary. The name of the user-defined function. |
UserData |
Optional. The value entered by the user as a parameter to the callback function. |
Tips and comments
Tip: You can set one or more parameters for a function.
Note: If the callback function needs to act directly on the value in the array, you can specify the first argument of the callback function as the reference:& $value. (see example 3)
Note: Passing the key name and UserData to the function is a new addition to PHP 4.0.
Example 1
<?php
function MyFunction ($value, $key) {
echo "The key $key has the value $value <br/>";
}
$a = Array ("A" => "Cat", "B" => "Dog", "C" => "Horse");
Array_walk ($a, "myfunction");
Output:
The key A has the value Cat
The key B has the value Dog
The key C has the value horse
Example 2
With one parameter:
<?php
function MyFunction ($value, $key, $p) {
echo "$key $p $value <br/>";
}
$a = Array ("A" => "Cat", "B" => "Dog", "C" => "Horse");
Array_walk ($a, "myfunction", "has the value");
? >
Output:
A has the value Cat
B has the value Dog
C has the value horse
Example 3
Change the value of an array element (Note & $value): (This situation is more!) )
<?php
function MyFunction (& $value, $key) {
$value = "Bird";
}
$a = Array ("A" => "Cat", "B" => "Dog", "C" => "Horse");
Array_walk ($a, "myfunction");
Print_r ($a);
Output:
Array ([a] => Bird [b] => Bird [c] => Bird)
Articles that you may be interested in
- PHP Array function array_map () notes
- PHP generates a continuous number (letter) Array function range () analysis, PHP lottery program function
- PHP finds whether a value exists in the array (In_array (), Array_search (), array_key_exists ())
- PHP presses the element to the array header (Array_unshift usage)
- PHP removes null-valued elements from the array (array_filter)
- How do I remove an element from a PHP array (unset,array_splice)?
- Use PHP function memory_get_usage to get current PHP memory consumption to achieve program performance optimization
- Summary of PHP array functions