Using array_walk_recursive() to Apply a User Function Recursively to Array Elements in PHP

This article explains the PHP function array_walk_recursive(), detailing its purpose, parameters, return values, and providing a complete example that demonstrates how to recursively apply a callback to array elements, including nested arrays, and shows the resulting output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using array_walk_recursive() to Apply a User Function Recursively to Array Elements in PHP

array_walk_recursive() applies a user-defined callback function to each element of an array, recursively traversing nested arrays.

Parameters

input : The array to be processed.

funcname : The callback function. It typically receives the value as the first argument and the key as the second; pass the value by reference if the function should modify the original array.

userdata (optional): Additional data passed as a third argument to the callback.

Return value : Returns TRUE on success, FALSE on failure.

Example

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

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

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

Output

a holds apple
b holds banana
sour holds lemon
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendprogrammingPHPArrayRecursioncallback
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.