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

Learn how to convert every number in an array of numbers 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]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.