Voting

: min(six, zero)?
(Example: nine)

The Note You're Voting On

bradbeattie at gmail dot com
14 years ago
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.

<?php
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.

<?php
/**
* 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.

<< Back to user notes page

To Top