|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #53039 Extend array_walk_recursive to provide context information to the callback func
Submitted: 2010-10-10 23:21 UTC Modified: 2010-10-14 07:37 UTC
From: monty at dontspam dot tamu dot edu Assigned:
Status: Wont fix Package: Arrays related
PHP Version: 5.3.3 OS: Windows Server
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2010-10-10 23:21 UTC] monty at dontspam dot tamu dot edu
It is easy to extend the array_walk_recursive function to be more useful in non-
trivial situations which require information about depth & path in the array 
structure the cursor is in, by adding an optional 4th parameter.  This would 
eliminate the need for MANY user-written depth first search traversal recursive 
functions.  Which consequently makes PHP a more attractive language for people 
fear recursion, but need a tree walk function which provides contextual 
information to the callback.

bool array_walk_recursive ( array &$input , callback $funcname [, mixed 
] [, array $state] )

where $state is a data dictionary having any number of context relevant data 
the depth of recursion (int), and the keys traversed to arrive at this node (a 
dimensional list array of string).

This enhancement is low risk: it would not break backward-compatibility.
This enhancement is high reward: it would make Xpath-like operations more 
approachable to the average developer.
This enhancement would simplify user code: which tends to increase security for 

Test script:
var $state = Array(
        $depth => 0
        ,$path => Array()

Expected result:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2010-10-14 07:37 UTC]
-Status: Open +Status: Wont fix
 [2010-10-14 07:37 UTC]
The RecursiveIteratorIterator, besides not working just with arrays, already provides such functionality.

$a = array(1, array(2.1, 2.2));
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach ($it as $el) {
    echo $el, " depth ", $it->getDepth(), "\n";

Your suggestion of using a variable where to store this information is also very inadvisable, if anything, it could be an extra argument passed to the callback function.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Jun 22 22:01:28 2024 UTC