Tác dụng của hàm array_walk_recursive()
The array_walk_recursive()
function apply a user-defined function recursively to every element of an array. This function is mainly used with deeper arrays (an array inside an array).
The following table summarizes the technical details of this function.
Return Value: | Returns TRUE on success or FALSE on failure. |
---|---|
Version: | PHP 5+ |
Syntax
The basic syntax of the array_walk_recursive()
function is given with:
The following example shows the array_walk_recursive()
function in action.
Example
Run this code »<?php
// Defining a callback function
function myFunction($item, $key){
echo "<p>$key holds $item</p>";
}
// Sample arrays
$pets = array("c" => "cat", "d" => "dog");
$animals = array("pets" => $pets, "wild" => "tiger");
array_walk_recursive($animals, "myFunction");
?>
Parameters
The array_walk_recursive()
function accepts the following parameters.
Parameter | Description |
---|---|
array | Required. Specifies the array to work on. |
callback | Required. Specifies the name of the user-defined callback function. The callback function typically takes on two parameters — the array value being the first, and the key/index second. |
userdata | Optional. Specifies a parameter to the user-defined callback function. It will be passed as the third parameter to the callback function. |
More Examples
Here're some more examples showing how array_walk_recursive()
function actually works:
You can also pass nested indexed array as a parameter to this function, as shown here:
Example
Run this code »<?php
// Defining a callback function
function myFunction($value, $index){
echo "<p>The value at index $index is $value</p>";
}
// Sample array
$colors = array("red", "green", "blue", array("white", "black"));
array_walk_recursive($colors, "myFunction");
?>