In PHP, the array_walk_recursive function can be used to apply a callback function to all elements in a multidimensional array. This article will introduce how to use the array_walk_recursive function.
In PHP, arrays can be multidimensional, that is, one array can contain another array. For example, the following array is a two-dimensional array:
$array = array( array('name' => 'john', 'age' => 20), array('name' => 'mary', 'age' => 25) );
array_walk_recursive function is used to apply a callback function to all elements in a multi-dimensional array. Its syntax is as follows:
array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool
Parameter description:
Returns true if successful, otherwise returns false.
The following is an example of using the array_walk_recursive function. Suppose we have a multidimensional array containing the names and ages of users, and we want to add 10 to each age and print out each user's name and new age.
function add_age(&$item, $key) { if ($key == 'age') { $item += 10; } } $array = array( array('name' => 'john', 'age' => 20), array('name' => 'mary', 'age' => 25) ); array_walk_recursive($array, 'add_age'); foreach ($array as $key => $value) { echo $value['name'] . ' ' . $value['age'] . '
'; }
In this example, we define a callback function add_age, which adds 10 to all ages. We then pass this callback function to the array_walk_recursive function, passing it our multidimensional array. Finally, we use a foreach loop to print out each user's name and new age.
The array_walk_recursive function can easily apply a callback function to all elements in a multidimensional array. It is very useful when dealing with multi-level nested arrays, which can avoid writing a lot of repeated code. We can use this function to complete various operations, such as data filtering, conversion, etc.
The above is the detailed content of How to use array_walk_recursive function in PHP to apply callback function to multi-dimensional array elements. For more information, please follow other related articles on the PHP Chinese website!