php.net |  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
 [2010-10-10 23:21 UTC] monty at dontspam dot tamu dot edu
Description:
------------
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 
who 
fear recursion, but need a tree walk function which provides contextual 
information to the callback.

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

where $state is a data dictionary having any number of context relevant data 
e.g. 
the depth of recursion (int), and the keys traversed to arrive at this node (a 
1-
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 
websites.

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

Expected result:
----------------
N/A

Actual result:
--------------
N/A

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-10-14 07:37 UTC] cataphract@php.net
-Status: Open +Status: Wont fix
 [2010-10-14 07:37 UTC] cataphract@php.net
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: Tue Dec 10 11:01:28 2024 UTC