Your variant using references (this does not solve your recursion problem, just FYI):
function make_abs(&$numbers)
{
foreach($numbers as &$value)
$value = abs($value)
;
}
For the recursion problem, you need to step into each array:
function make_abs(&$numbers)
{
foreach($numbers as &$value)
is_array($value) ? make_abs($value) : $value = abs($value)
;
}
PHP itself has a somewhat handy function for that, array_walk_recursive
Docs. The problem with that function is, it expects the callback to have two parameters, value (by reference) and key. Many PHP functions do not fit those requirements. You can work around that by creating yourself a helper function to use any function that only takes one parameter and returns the modified value. You pass the function as with array_map
Docs:
function array_walk_recursive_map(array &$array, $callback)
{
$byRef = function(&$item, $key) use ($callback)
{
$item = $callback($item);
};
array_walk_recursive($array, $byRef);
}
# Usage:
array_walk_recursive_map($numbers, 'abs');
Hope this is helpful.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…