PHP Function Reference

PHP array_walk_recursive() Function



The PHP array_walk_recursive() function applies the user-defined function to each element of the array. This function is not affected by the internal array pointer of array and walk through the entire array regardless of pointer position. This function recurses into deeper arrays.

Syntax

array_walk_recursive(array, myfunction, arg)

Parameters

array Required. Specify the input array.
myfunction Required. Specify user-defined function. Typically it takes two parameters. First parameter as array's value and second parameter as array's key. A third parameter can be passed using arg parameter of the array_walk_recursive() function. Please note that only the values of the array may potentially be changed.
arg Optional. If provided, it is passed as the third parameter to the myfunction.

Note: If myfunction needs to be working with the actual values of the array, specify the first parameter of myfunction as a reference. Then, any changes made to those elements will be made in the original array itself.

Return Value

Returns true on success or false on failure.

Exceptions

NA.

Example:

In the example below, the array_walk_recursive() function is used to print the content of the array.

<?php
function MyFunc1($value, $key) {
  echo "$key = $value \n";
}

function MyFunc2($value, $key, $p) {
  echo "$key $p $value. \n";
}

$Arr = array("Red"=>10, "Green"=>20, "Blue"=>30,
             "others"=>array("White"=>0, "Black"=>1));

array_walk_recursive($Arr, 'MyFunc1');
echo "\n";
array_walk_recursive($Arr, 'MyFunc2', 'has the value');
?>

The output of the above code will be:

Red = 10 
Green = 20 
Blue = 30 
White = 0 
Black = 1 

Red has the value 10. 
Green has the value 20. 
Blue has the value 30. 
White has the value 0. 
Black has the value 1. 

Example:

Consider one more example where value is passed as reference. Any changes made to these values will change the original array itself.

<?php
function MyFunc(&$value, $key) {
  $value = $value**3;
}

$Arr = array(1, 2, 3, 4, 5, array(10, 20));

echo "Before applying array_walk_recursive() function:\n";
print_r($Arr);

//applying array_walk_recursive() function
array_walk_recursive($Arr, 'MyFunc');

echo "\nAfter applying array_walk_recursive() function:\n";
print_r($Arr);
?>

The output of the above code will be:

Before applying array_walk_recursive() function:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => Array
        (
            [0] => 10
            [1] => 20
        )
)

After applying array_walk_recursive() function:
Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
    [5] => Array
        (
            [0] => 1000
            [1] => 8000
        )
)

❮ PHP Array Reference