PHP array_walk Apply user-defined functions to each element in an array
Array_walk use user-defined functions to do callback for each element in the array
Basic syntax
BOOL Array_walk (array & $array, callable $funcname [, mixed $userdata = NULL])
Applies the user-defined function funcname to each cell in an array.
Array_walk () is not affected by array pointers within the array. Array_walk () traverses the entire array regardless of the position of the pointer.
Parameter introduction:
Parameters |
Description |
Array |
Necessary. The array entered. |
Funname |
Necessary. The name of the user-defined function. Typically, the funcname accepts two parameters. The value of the array parameter is the first, and the key name is the second. If funcname needs to act directly on the values in the array, the first argument to FuncName is specified as a reference. Any changes to these units will also change the original array itself. |
UserData |
Optional. Specify the parameters of the user-defined function. If an optional parameter userdata is provided, it is passed as the third argument to callback funcname. |
Description
The 1.array_walk () function applies a callback function to each element in the array. Returns TRUE if successful, otherwise returns FALSE.
2. Typically, the Funname 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.
3. If the Funname function requires more arguments than is given, a e_warning-level error will be generated each time the Array_walk () call Funname. These warnings can be suppressed by adding PHP's error operator @ before the Array_walk () call, or by using error_reporting ().
4. 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 a reference.
return value
Returns TRUE on success or FALSE on failure.
Instance:
<?php
$fruits = Array (
"D" => "Lemon",
"a" => "orange",
"B" => "banana",
"C" => " Apple "
);
Function Test_alter (& $item 1, $key, $prefix) {
$item 1 = "$prefix: $item 1";
}
function Test_print ($item 2, $key) {
echo $key. $item 2 <br/> ";
}
echo "before ...: <br/>";
Array_walk ($fruits, ' test_print ');
Array_walk ($fruits, ' test_alter ', ' fruit ');
echo "... and after:<br/>";
Array_walk ($fruits, ' test_print ');
? >
Run Result:
Before ...:
D. Lemon
A. Orange
B. Banana
C. Apple
.. and After:
D. Fruit:lemon
A. Fruit:orange
B. Fruit:banana
C. Fruit:apple
Thank you for reading, I hope to help you, thank you for your support for this site!