php8.5
Home/ Manual/ array / functions/ array_walk_recursive

array_walk_recursive

PHP function Edit on GitHub ✎

(PHP 5, PHP 7, PHP 8)

Apply a user function recursively to every member of an array

Description

array_walk_recursive(array|object $array, callable $callback, mixed $arg = null): true

Applies the user-defined callback function to each element of the array. This function will recurse into deeper arrays.

Passing an object as the array is allowed, and will be treated as if it had been cast to an array first. Regardless of whether the function started with an array or an object, it will not recurse into inner objects.

Parameters

array

The input array.

callback

Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.

Note

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

arg

If the optional arg parameter is supplied, it will be passed as the third parameter to the callback.

Return Values

Always

Changelog

VersionDescription

Examples

array_walk_recursive() example

php
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

The above example will output:

output
a holds apple
b holds banana
sour holds lemon

You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function.

array_walk_recursive() can also be used to update values in place by passing the callback parameter by reference.

Updating values in place

php
<?php
$sweet = ['a' => 'apple', 'b' => 'banana'];
$fruits = ['sweet' => $sweet, 'sour' => 'lemon'];

function test_update(&$item)
{
    $item = strtoupper($item);
}

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_update');
array_walk_recursive($fruits, 'test_print');
?>

The above example will output:

output
a holds APPLE
b holds BANANA
sour holds LEMON

See Also

Source: reference/array/functions/array-walk-recursive.xml · from the official PHP manual (php/doc-en)