PHP’s array_walk_recursive

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 to alter $array to get a short slice of each value
 *    array_walk_recursive_by_reference(
 *        $array, "substr", array("1","3")
 *    );
 */
function array_walk_recursive_by_reference(
        &$array, $function, $parameters = array()) {
    $reference_function = function(&$value, $key, $data) {
        $parameters = array_merge(array($value), $data[1]);
        $value = call_user_func_array($data[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.

Leave a Reply