php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #54076 Feature request - function array_walk_recursive
Submitted: 2011-02-22 21:56 UTC Modified: -
From: Tor-Martin at storsletten dot com Assigned:
Status: Open Package: Arrays related
PHP Version: 5.3.5 OS: All
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2011-02-22 21:56 UTC] Tor-Martin at storsletten dot com
Description:
------------
---
From manual page: http://www.php.net/function.array-walk-recursive#Parameters
---

This function does not send arrays to the callback function, and in most cases this is what you want, but sometimes you may need at least the keys of the arrays (example below). My suggestion is to add a fourth parameter to this function which takes a boolean value, and defaults to FALSE. The callback function can then handle the arrays and their keys if this parameter is set to TRUE.

One usage for this feature would be if you want to make a custom function for serializing an array and all its content. A serialized string must contain the keys of child arrays, else the custom unserializer will be unable to restore child arrays properly. A custom serializer may be able to make binary strings rather than human-readable strings like serialize() does, which will save a lot of space e.g. when storing $_SESSION data in a database.

Additionally, this feature would also allow custom output of arrays in a human-friendly way, especially if the callback function can get the depth of the iteration (see the code example below).

Test script:
---------------
function awr_callback(&$val, &$key, &$ptr, $depth = 0) {
 $indent = str_pad('', $depth, ' ');
 if (is_array($val)) $ptr[0] .= "${indent}Array '$key' (" . count($val) . "):\n";
 elseif (is_string($val)) $ptr[0] .= "${indent}String '$key' (" . strlen($val) . "): $val\n";
 // ...
}

$a = array('beginning', 'first child' => array('an element', 'another element'), 'end');
$s = '';
array_walk_recursive($a, 'awr_callback', array(&$s), true);
echo $s;

// This short example is written to demonstrate usage of the suggested features, and will not work with the current version of PHP.

Expected result:
----------------
Expected output when/if the features are implemented:

String '0' (9): beginning
Array 'first child' (2):
 String '0' (10): an element
 String '1' (15): another element
String '1' (3): end

Actual result:
--------------
Actual output (if you first remove the fourth input parameter when calling array_walk_recursive):

String '0' (9): beginning
String '0' (10): an element
String '1' (15): another element
String '1' (3): end

Patches

Add a Patch

Pull Requests

Add a Pull Request

 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Thu Jun 27 07:01:41 2019 UTC