PHP array_walk_recursive() Function

PHP array_walk_recursive() Function

The array_walk_recursive () function in PHP is used to apply a user-defined callback function recursively to each element of the array. This function returns a Boolean TRUE on success or FALSE on failure.

Syntax

array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] )

Parameter

array(required)- This array represents the input array.

callable(required)- It takes two parameters. The first one is the array parameter's value, and the second one is the key/index.

userdata(optional)- This parameter represents an extra parameter, and it will be passed as the third parameter to the callback. The default value is null.

Return

This function returns a Boolean value TRUE on success or FALSE on failure.

Example 1

 'watermelon', 'b' => 'banana','c'=>'mango');
 $fruits = array('summer' => $summer, 'winter' => 'strawberry', 'cherry');
 //initializing the function
 function myFunction($item, $key)
 {
     echo "$key holds $item\n";
 } 
 //applying the function for each element of the array
 array_walk_recursive($fruits, 'myFunction');
 ?> 

Output

a holds watermelon
b holds banana
c holds mango
winter holds strawberry
0 holds cherry 

Example 2

 'Reema', 'b' => 'Raj', 'c'=>'Monica');
 $fruits = array($name, 'class' => 'B.Tech');
 //initializing the function
 function myFunction($item, $key)
 {
     echo "The $key holds $item\n"; 
 }
 //applying the function for each element of the array
 array_walk_recursive($fruits, 'myFunction');
 ?> 

Output

The a holds Reema
The b holds Raj
The c holds Monica
The class holds B.Tech 

Example 3

"red","b"=>"green","c"=>"blue");
 //applying the function for each element of the array
 array_walk_recursive($array,"myfunction","has the value");
 ?> 

Output

The key 'a' has the value red
The key 'b' has the value green The key 'c' has the value blue