Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Which is the easy way of getting the abs of an array in php? It has to be a better way. This works, but in multidimensional array it has some limitations

function make_abs($numbers) {
 $abs_array = array();

 foreach($numbers as $key=>$value)
   $abs_array[$key] = abs($value);

 return $abs_array;
}
question from:https://stackoverflow.com/questions/65928064/absolute-value-implode

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

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_recursiveDocs. 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_mapDocs:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...