phparraysexplodeprefiximplode

Add a prefix to each item of a PHP array


I have a PHP array of numbers, which I would like to prefix with a minus (-). I think through the use of explode and implode it would be possible but my knowledge of php is not possible to actually do it. Any help would be appreciated.

Essentially I would like to go from this:

$array = [1, 2, 3, 4, 5];

to this:

$array = [-1, -2, -3, -4, -5];

Any ideas?


Solution

  • Simple:

    foreach ($array as &$value) {
       $value *= (-1);
    }
    unset($value);
    

    Unless the array is a string:

    foreach ($array as &$value) {
        $value = '-' . $value;
    }
    unset($value);