How to Convert All Numbers in a PHP Array to Absolute Form?

In PHP, you can convert all numbers in an array of numbers (consisting of int and/or float values) to their absolute form, for example, in the following way:

// PHP 8+
$arr = [1234, -5678, 12.34, -56.78];
$newArr = array_map(fn (int|float $num) => abs($num), $arr);

var_dump($newArr); // [1234, 5678, 12.34, 56.78]

This works by calling the abs() function on every element of the array using the array_map() function.

You can rewrite the callback to array_map() without union type and arrow function to make it compatible with earlier versions of PHP.

The code above would create a new array with all numbers in the array in absolute form. You can achieve the same with a simple for loop as well:

$arr = [1234, -5678, 12.34, -56.78];
$newArr = [];

foreach ($arr as $num) {
    $newArr[] = abs($num);
}

var_dump($newArr); // [1234, 5678, 12.34, 56.78]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.