What Is array_walk_recursive?

array_walk_recursive applies a user-defined function to each element of a multidimensional array. It works by iterating through all nested levels of the array.

In our custom implementation, we will manually traverse each array level using recursion and apply the callback function.

Custom Implementation of array_walk_recursive

Here’s how you can create a custom array_walk_recursive function in PHP:

function customArrayWalkRecursive(&$array, $callback) {
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            // Recursive call for nested arrays
            customArrayWalkRecursive($value, $callback);
        } else {
            // Apply callback to the value
            $callback($value, $key);
        }
    }
}

// Sample multidimensional array
$data = [
    "name" => "Dharmender",
    "details" => [
        "age" => 30,
        "location" => "Bangalore",
    ],
    "hobbies" => [
        "sports" => ["soccer", "basketball"],
        "music" => "guitar"
    ]
];

// Callback function to modify each element
$callback = function (&$value, $key) {
    $value = strtoupper($value); // Convert each value to uppercase
};

// Apply custom recursive function
customArrayWalkRecursive($data, $callback);

// Output the modified array
print_r($data);

Example of Custom array_walk_recursive:

Output:

Array
(
    [name] => Dharmender
    [details] => Array
        (
            [age] => 30
            [location] => Bangalore
        )

    [hobbies] => Array
        (
            [sports] => Array
                (
                    [0] => SOCCER
                    [1] => BASKETBALL
                )

            [music] => GUITAR
        )
)

Benefits of Custom Implementation

  1. Flexibility: You can modify the logic as needed.
  2. Control: Handle recursion manually for deeper understanding.
  3. Educational Value: Learn how recursion works in PHP.

Implementing array_walk_recursive manually is a valuable exercise for understanding recursion and array traversal in PHP. With the custom function, you can achieve similar results to the built-in function while having full control over the logic.

This method is useful for scenarios where built-in functions are restricted or if you want a tailored solution.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *