• :
  • :

array_walk_recursive: how to use with examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

what is array_walk_recurisve

Description

Applies a callback function recursively to every array element

Function Signature

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

Arguments

  • array – The input array
  • callback – A function that is applied recursively to every array element. The callback function takes two arguments. First argument is the value/element and second is the key.
  • arg – If this optional argument is passed then it will be passed as the third argument to the callback.

Return Value

True on success else returns False.

Introduction

We have seen multi-dimensional arrays in PHP. These are arrays within arrays that could span several levels. Often programmers visualize a multidimensional array using a tree structure. A tree structure signifies the parent child relationship pretty well. In fact, the most famous data structures known as graphs and trees could be implemented using arrays. However, that’s not the topic here. 

In this article, we’re going to see a recursive function that could dig deep into an array and apply a function to nodes that could be several levels deep. Unlike the foreach loops where we need to nest as many loops as the number of levels in a multidimensional array, the recursive approach eliminates the concern of levels of depth. We have briefly discussed iterative and recursive approaches in one of the articles.

Here we will explore a PHP function array_walk_recursive. This function has the capability to recursively apply a callback function to every member of an array regardless of how nested it is within the parent array. But before we see explore this function, we’ll see the multi-dimensional array that we would be using in the subsequent examples as well as the tree diagram.

Students Data Array

The multidimensional array that we will be using in the subsequent examples contains students course related data and is several levels deep. The following tree diagram will easily visualize the number of levels and the parent child relationship between the arrays. 

Students Array$students = [
                "Mark"=>[
                            "Quizes"=>[10,9,10],
                            "Electives"=>[
                                            ["ComputerScience"=>["CreditHours"=>4,"Grade"=>"A"]]
                                        ]
                        ],
 
                "Anna"=>[
                            "Quizes"=>[8,9,5], 
                            "Electives"=>[
                                            ["Economics"=>["CreditHours"=>3,"Grade"=>"B+"]]
                                         ]
                        ],
 
                "Ruby"=>
                        [
                            "Quizes"=>[2,3,10],
                            "Elective"=>[
                                            ["Electronics"=>["CreditHours"=>4,"Grade"=>"C"]]
                                        ]
                        ]
            ];

Tree Diagram

array_walk_recursive

The diagram shows the Students Array as the root node or the parent node of all the nodes that branches from it either directly or indirectly. The CreditHours and Grades are at the maximum depth and these are therefore known as the leaf nodes. Can you sort out the max depth? 


If your answer is five then you know the tree well. Don’t worry if you didn’t because the terminologies introduced above are enough to understand the following examples and explanations. So, let’s jump to the anatomy of the array_walk_recursive function.

Usage Example#1 

Let’s see how to use this function. We will be using PHP array walk on the Students Array and simply print out the key and values to the console to see what we get as output.

Example#1array_walk_recursive($students,function($value,$key) {
    print_r("Here is the key: ".$key." holding value: ".$value.PHP_EOL);
});
 
/*OUTPUT
Here is the key: 0 holding value: 10
Here is the key: 1 holding value: 9
Here is the key: 2 holding value: 10
Here is the key: CreditHours holding value: 4
Here is the key: Grade holding value: A      
Here is the key: 0 holding value: 8
Here is the key: 1 holding value: 9
Here is the key: 2 holding value: 5
Here is the key: CreditHours holding value: 3
Here is the key: Grade holding value: B+     
Here is the key: 0 holding value: 2
Here is the key: 1 holding value: 3
Here is the key: 2 holding value: 10
Here is the key: CreditHours holding value: 4
Here is the key: Grade holding value: C
*/

Important Caveat

Look at the output closely, it is obvious that the array_walk_recursive function prints out leaf nodes only. This is a fact often neglected when you read the official documentation of the function. Therefore, we have explored that this function visits the leaf nodes only. The leaf nodes could be at any depth.

Usage Example#2

Let’s take a step further. We know that the function deals with the leaf nodes. Luckily, the Quizzes have a number array that is the leaf node. Hence, the function prints it out. Let’s assume we have to change these marks and scale them by 10 (Add 10 to each quiz). Let’s try to do it.

Example#2array_walk_recursive($students,function($value,$key) {
    if(gettype($key) == "integer")
    {
        $value += 10;
    }
});
 
foreach($students as $key=>$value)
{
    print_r("The quizes marks of ".$key." are ".implode(" ",$value["Quizes"]).PHP_EOL);
}
 
/*OUTPUT
The quizes marks of Mark are 10 9 10
The quizes marks of Anna are 8 9 5  
The quizes marks of Ruby are 2 3 10 
*/

Oops! The marks didn’t change. Why though? That’s because the array is passed by value, not by reference to the function. Pass by value vs reference is an important concept in programming. So how to go about this problem? 

The solution is to pass the first argument to the callback function by reference. In PHP reference arguments are passed by prepending & to them. So, let’s do that.

Example#2 - Correctedarray_walk_recursive($students,function(&$value,$key) {
    if(gettype($key) == "integer")
    {
        $value += 10;
    }
});
 
foreach($students as $key=>$value)
{
    print_r("The quizes marks of ".$key." are ".implode(" ",$value["Quizes"]).PHP_EOL);
}
 
/*OUTPUT
The quizes marks of Mark are 20 19 20
The quizes marks of Anna are 18 19 15
The quizes marks of Ruby are 12 13 20
*/

 Voila! Works like a charm now. Observe the &$value. Here the array elements are passed by reference and thus any change that happens within the callback function is reflected in the original array. Therefore, we have an important caveat here as well.

Important Caveat

If you intend to change values in the multidimensional array through PHP array walk then you’ve to pass the first argument of the callback function by reference. Otherwise, the change would never be reflected in the original array.

When to use array_walk_recursive?

Now as we know that the function visits the leaf nodes only then do we have a good practical use for it? The question is crucial because we usually aim to recurse or iterate over the entire tree rather than just the leaf nodes.

Well, that’s the limitation of array_walk_recursive but that doesn’t make it entirely useless because sometimes in server response we might need to visit the leaf nodes without worrying about the depth of these nodes. In practice, these nodes might be many levels deep. That’s why PHP array walk conveniently fetches these leaves for us which could otherwise be impractical with the iterative approach.

Conclusion

In this article, we have seen PHP array_walk_recursive function and explored some important caveats that are not so obvious from the general description of the function. The two important caveats are that the function visits the leaf nodes only and secondly, the callback function should get the first argument by reference if it is supposed to make changes to the original array.

With these facts in mind, you’re now well familiar with this function and could use it where seems appropriate. That’s all for this article. Stay tuned for more interesting PHP articles and tutorials.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Search for multiple values in PHP array

How to filter array of objects by value in PHP

How to filter array of objects by key in PHP

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.