note 99639 added to function.array-walk-recursive

From: Date: Fri, 27 Aug 2010 18:18:13 +0000
Subject: note 99639 added to function.array-walk-recursive
Groups: php.notes 
Request: Send a blank email to php-notes+get-172118@lists.php.net to get a copy of this message
The description says "If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference." This isn't necessarily helpful as the function you're calling might be built in (e.g. trim or strip_tags). One option would be to create a version of these like so. function trim_by_reference(&$string) { $string = trim($string); } The downside to this approach is that you need to create a wrapper function for each function you might want to call. Instead, we can use PHP 5.3's inline function syntax to create a new version of array_walk_recursive. /** * This function acts exactly like array_walk_recursive, except that it pretends that the function * its calling replaces the value with its result. * * @param $array The first value of the array will be passed into $function as the primary argument * @param $function The function to be called on each element in the array, recursively * @param $parameters An optional array of the additional parameters to be appeneded to the function * * Example usage to alter $array to get the second, third and fourth character from each value * array_walk_recursive_referential($array, "substr", array("1","3")); */ function array_walk_recursive_referential(&$array, $function, $parameters = array()) { $reference_function = function(&$value, $key, $userdata) { $parameters = array_merge(array($value), $userdata[1]); $value = call_user_func_array($userdata[0], $parameters); }; array_walk_recursive($array, $reference_function, array($function, $parameters)); } The advantage here is that we only explicitly define one wrapper function instead of potentially dozens. ---- Server IP: 216.235.13.26 Probable Submitter: 208.70.247.145 ---- Manual Page -- http://www.php.net/manual/en/function.array-walk-recursive.php Edit -- https://master.php.net/note/edit/99639 Del: integrated -- https://master.php.net/note/delete/99639/integrated Del: useless -- https://master.php.net/note/delete/99639/useless Del: bad code -- https://master.php.net/note/delete/99639/bad+code Del: spam -- https://master.php.net/note/delete/99639/spam Del: non-english -- https://master.php.net/note/delete/99639/non-english Del: in docs -- https://master.php.net/note/delete/99639/in+docs Del: other reasons-- https://master.php.net/note/delete/99639 Reject -- https://master.php.net/note/reject/99639 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#172118) next »