Expand To Show Full Article
Change array_walk_recursive() Value: PHP Code Examples - Fueling PHP
Skip to content
Home » Change array_walk_recursive() Value: PHP Code Examples

Change array_walk_recursive() Value: PHP Code Examples

Summary

There are 2 ways you can change the value in array_walk_recursive. You can use a pass-by-value or a pass-by-reference approach. You should use a pass-by-value strategy most of the time, but there are cases where pass-by-reference is well-suited.

Functions Mentioned in this Post

Recursion is an essential concept in computer science and programming. In simpler terms, it is a process of breaking down a problem into sub-problems and then solving these sub-problems using a common approach. It is a better alternative to the iterative approach, which can sometimes affect the performance.

change the value in array_walk_recursive

Recursion usually involves a function that calls itself over and over unless it meets an exit condition. This approach is frequently used in recursion problems. If you want to know further about recursion, see it in action in generating the Fibonacci sequence. Here we will use PHP built-in function that performs recursion over an iterable data structure, an array.

change the value in array_walk_recursive

PHP array_walk_recursive function provides a convenient way to dig deep into a multidimensional array without much hassle. However, an important caveat to keep in mind is that it gets down to the leaf nodes. So, any access or modification applies to the values at the innermost arrays or, in other words, the leaf nodes.

We have already seen the array_walk_recursive function in great detail. In this article, we will see how to change the value in array_walk_recursive. Before that, we will do a recap of the array_walk_recursive function by an example.

PHP array_recursive_function: A recap

PHP array_recursive_function can recurse a multidimensional array from the topmost array to the innermost. However, it accesses and modifies the innermost array values. These innermost array values are said to be the leaf nodes of a tree. A tree could be derived based on the structure of the array.
Let’s suppose we have a student array like this.

$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"]]
                                        ]
                        ]
            ];

Here’s the tree diagram of the array.

So, the function will access the values at the leaf nodes. Let’s see that through an example.

Usage Example

array_walk_recursive($students,function($value,$key) {
     print_r($value." ");
});
 
//OUTPUT
//10 9 10 4 A 8 9 5 3 B+ 2 3 10 4 C

Observe that it gets down to the values located at the innermost arrays. After this recap, let’s get to the main question, how to change the value in array_walk_recursive PHP function?

How to change the value in array_walk_recursive PHP function

Before diving into complexities, let’s modify the quiz marks in each student subarray using array_walk_recursive. Just because the quiz marks are the leaf nodes, the function should be able to change them. Let’s scale them by adding 10 to each score.

array_walk_recursive($students,function($value,$key) {
    if(gettype($key) == "integer")
    {
        $value += 10;
    }
});
 
foreach($students as $student) {
    print_r($student['Quizes']);
}
 
/*
OUTPUT
Array        
(
    [0] => 10
    [1] => 9
    [2] => 10
)
Array        
(
    [0] => 8
    [1] => 9
    [2] => 5
)
Array        
(
    [0] => 2
    [1] => 3
    [2] => 10
)
*/

As you can see, the function doesn’t change the values. So, it isn’t relatively straightforward. However, there’s a way out, and that’s by passing the value by reference. 

Passing by Reference vs Passing by Value

Passing a variable by reference means that we pass the memory address of the variable, allowing a function to change the variable by accessing it through the address. Remember that memory addresses work just like home addresses. This fact implies that the change happens at one place to a similar variable.

Passing a variable by value is equivalent to passing a copy of the variable to the function, allowing it to change the copy rather than the original.

Change the value in array_walk_recursive function

PHP passes a variable by reference if we prepend an & to the variable name. So, we will prepend an & to the value parameter in the array_walk_recursive function.

array_walk_recursive($students,function(&$value,$key) {
    if(gettype($key) == "integer")
    {
        $value += 10;
    }
});
 
foreach($students as $student) {
    print_r($student['Quizes']);
}
 
/*
OUTPUT
Array        
(
    [0] => 20
    [1] => 19
    [2] => 20
)
Array        
(
    [0] => 18
    [1] => 19
    [2] => 15
)
Array        
(
    [0] => 12
    [1] => 13
    [2] => 20
)
*/

Voila! The function changes the values this time. Have you noticed the & before value in the parameter. That’s how to change the value in array_walk_recursive.

Important Caveat

While this technique works for values, it doesn’t work for keys. There is no particular explanation, but this is how the function behaves. It throws a warning if you try to pass the key by reference. So, it couldn’t modify the key values.

Conclusion

In this article, we have seen how to change the value in array_walk_recursive function in PHP. This function recursively accesses the values at the innermost arrays within a multidimensional array. However, changing these values is not straightforward and requires these values by reference to modify them. We hope you have learned something new today. Stay tuned for more exciting PHP articles.