Skip to content
Home » Return Specific array_walk_recursive Value: PHP Code Examples

Return Specific array_walk_recursive Value: PHP Code Examples

Summary

If you want to return a value from the array_walk_recursive function then you should implement the 'use' keyword to pass in a variable reference. Once passed, you can update the variable in the function and then the value will be available for return when it is finished.

Functions Mentioned in this Post

PHP array_walk_recursive function recursively applies a callable to every element of an array. We have an in-depth article about the array_walk_recursive PHP. One of the most incredible things about this function is that it accesses the innermost elements of a multidimensional array in PHP. 

The alternative approach of iterating over a multidimensional array is nested loops that are computationally expensive and affect performance. So, the array_walk_recursive is ideal if you want to target the innermost elements.

This article will focus on a particular aspect of this function: how to return a specific value in array_walk_recursive PHP function. However, we will review this function so that we have enough background to keep things in perspective. That’s why we’ll first walk you through a brief overview of this function, followed by the main subject of returning a specific value in the array_walk_recursive function.

The array_walk_recursive PHP: A review

As mentioned, the function recursively applies a callable to every element of an array. The callable refers to a function that could be a PHP built-in or user-defined function.

Every element of an array is generic because the function is specialized to run the innermost elements of a multidimensional array. If we could visualize a multidimensional array as a tree, then the innermost elements translate to the leaf nodes.

array_walk_recursive PHP Code Example

Here’s a PHP multidimensional array having data of students.

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

We can visualize it by laying down a tree diagram as follows.

array_walk_recursive PHP

Can you see the leaf nodes? The function applies a callable to the leaf nodes. Let’s confirm it through code.

array_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
*/

So, it prints the leaf nodes only, which confirms our point. We have more examples in our array_walk_recursive article. Don’t miss it out.

Before we move on to the main topic, I would list some important caveats here.

  • The array_walk_recursive applies the callable to the leaf nodes only.
  • If you intend to change values in the multidimensional array through PHP array_walk_recursive, you’ve to pass the first argument of the callback function by reference.

Next, let’s move to the main question: How to return a specific value in array_walk_recursive PHP function.

Return a specific value in array_walk_recursive Example

Let’s jump to the example and see if the function can increment a global variable count value.

$names = ["Richard", "Sophie", "Diana", "David", "Kevin"];
 
//Initialize the count to zero.
$count = 0;
 
array_walk_recursive($names,function($v,$k) {
    $count++;
});

Oops! The example throws an error because the function cannot access th count variable. However, there’s a way out as we can pass the third argument to the function, which would become a third argument to the callable.

array_walk_recursive($names,function($v,$k,$count) {
    $count++;
    echo $count.PHP_EOL;
},$count);
 
 
//The count should be 5.
print_r($count);
 
/*
OUTPUT
1
1
1
1
1
0
*/

The example no longer throws an error, but as we can see, the value of count doesn’t persist either inside the function body or in the global context. Let’s build on the existing example and pass the count by reference this time.

//Initialize the count to zero.
$count = 0;
 
array_walk_recursive($names,function($v,$k) use(&$count) {
    $count++;
    echo $count.PHP_EOL;
}, $count);
 
 
//The count should be 5.
print_r($count);
 
/*
OUTPUT
1
2
3
4
5
5
*/

oila! We get persistence by using the PHP “use” keyword and reference value for count instead.  This idea is essential because we couldn’t store a specific value from the array_walk_recursive PHP.

How to return a specific value in array_walk_recursive PHP function

So, let’s use an array and return a developer name who knows “React.”

<?php
$developers = [
    "Nancy" => "PHP",
    "Karen" => "Android",
    "David" => "Javascript",
    "Tyson" => "Flutter",
    "Richard" => "React"
];
 
$name = '';
 
array_walk_recursive($developers, function(&$v,$k) use(&$name) {
   
    if($v == "Android") {
        $name = $k;
    }
}, $name);
 
print_r($name);
 
/*
OUTPUT
Karen
*/
 
?>
 

Voila! We have used almost the same code as we did in the previous example. That’s how we can get a specific value from the array_walk_recursive PHP.

Conclusion

In this article, we have reviewed the PHP array_walk_recursive and learned how to return a specific value in array_walk_recursive PHP. Using reference variables and the “use” keyword in PHP, we could persist a value even if the function terminates. So, that’s all for this article. Stay tuned for more informative PHP tutorials and articles.

Want to explore more useful PHP tutorials?

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

How to merge 2 arrays with the same keys in PHP

Difference between array_merge and array_merge_recursive in PHP

Difference between array_combine and array_merge in PHP