How to Negate 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]

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.