PHP Array Function array_walk () Notes
Definition and usage
The array_walk () function applies a callback function to each element in the array. If the call succeeds, TRUE is returned. Otherwise, FALSE is returned.
In typical cases, a function accepts two parameters. The value of the array parameter is the first and the key name is the second. If the optional parameter userdata is provided, it is passed to the callback function as the third parameter.
If the function requires more parameters than the given parameter, an E_WARNING error is generated every time array_walk () calls the function. These warnings can be suppressed by adding the PHP error operator @ before the array_walk () call, or error_reporting ().
Syntax
Array_walk (array, function, userdata ...)
| Parameters |
Description |
| Array |
Required. Specified array. |
| Function |
Required. The name of the User-Defined Function. |
| Userdata |
Optional. The value that you enter can be used as a callback function parameter. |
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 values in the array, you can specify the first parameter of the callback function as reference: & $ value. (See example 3)
Note: passing the key name and userdata to the function is newly added to PHP 4.0.
Example 1
<?phpfunction 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 a parameter:
<?phpfunction 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 the array element (Note & $ value): (this situation is often used !)
<?phpfunction 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 you may be interested in
- PHP Array Function array_map () Notes
- PHP generates continuous numbers (letters) Array Function range () analysis, PHP lottery program function
- Php searches for the existence of a value in the array (in_array (), array_search (), array_key_exists ())
- Php pushes an element to the array header (array_unshift usage)
- PHP removes the null element from the array (array_filter)
- How to delete elements (unset, array_splice) in the PHP array )?
- Introduction to array union, intersection, and difference set functions in php
- Use the PHP function memory_get_usage to obtain the current PHP memory consumption for program performance optimization.