How to Negate All Numbers in a PHP Array?

Find out how to flip all numbers in a PHP array

In PHP, you can negate all numbers in an array of numbers by applying the negation operator (-) on every element of the array using array_map(), for example, like so:

// PHP 7.4+
$arr = [3, 2, -1, 0, 4, -6, -5];
$newArr = array_map(fn (int|float $num): int|float => -$num, $arr);

var_dump($newArr); // [-3, -2, 1, -0, -4, 6, 5]

You can rewrite the callback to array_map() without 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 negated (i.e. positive numbers will be flipped to negative and negative numbers will be converted to positive). You can achieve the same with a simple for loop as well:

$arr = [3, 2, -1, 0, 4, -6, -5];
$newArr = [];

for ($i = 0; $i < count($arr); $i++) {
    $newArr[] = -$arr[$i];
}

var_dump($newArr); // [-3, -2, 1, -0, -4, 6, 5]

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