91

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?

Dávid Horváth
  • 4,050
  • 1
  • 20
  • 34
MBL
  • 1,197
  • 2
  • 11
  • 17

8 Answers8

171

An elegant way to prefix array values (PHP 5.3+):

$prefixed_array = preg_filter('/^/', 'prefix_', $array);

Additionally, this is more than three times faster than a foreach.

Dávid Horváth
  • 4,050
  • 1
  • 20
  • 34
  • 9
    I find this the best answer mainly while it's so much faster. Also worth mentioning is [`preg_replace`](http://php.net/manual/en/function.preg-replace.php), it does roughly the same but it always returns a same-sized array with the unmodified item for items that doesn't match the regex. It's also a bit lighter on the version requirements (exists in PHP4 vs `preg_filter` which requires PHP >= 5.3.0). – dbm Apr 02 '15 at 09:10
  • 1
    is there any way to add a suffix? – AvikB Mar 27 '16 at 08:11
  • 18
    @Avik To add a suffix just use the `$` anchor: `preg_filter('/$/', '_suffix', $array);` – Dávid Horváth Mar 27 '16 at 15:50
  • For more information about regular expressions in PHP read the PCRE manual: http://php.net/manual/en/reference.pcre.pattern.syntax.php – Dávid Horváth Mar 27 '16 at 16:00
  • 2
    thanks, i figured this out `preg_filter('/^(.*?)$/', '$0*', $array)`, it does work, but i like yours, it is short. thanks again really appreciate the help :) – AvikB Mar 27 '16 at 16:29
  • This is awesome. It should definitly be the accepted answer for so many reasons. It is faster than a `foreach`, it moves the cyclomatic complexity to the internal sub-level of PHP and it can be used for prefix, suffix or change any part of the values of your array when you find a pattern to detect where the modification has to be done. I need to keep this function in my mind. Thank you. – niconoe Jan 12 '17 at 09:02
  • I like this better than any other answers. I formerly use `array_walk` function but now I've changed to this way. Thank you so much! – Taufik Nur Rahmanda Aug 28 '17 at 01:40
  • can this method use array `key` to be the prefix of the `value`? I know `foreach` & `array_walk` can, but I wonder if this also – Taufik Nur Rahmanda Dec 29 '17 at 03:58
  • @TaufikNurRahmanda There are only a few functions in PHP that instantly combine keys with their values (`http_build_query`, for example). To my knowledge PCRE can't do this. – Dávid Horváth Dec 30 '17 at 14:32
  • 1
    Thanks, this is the best answer, but I prefer `preg_replace` by the way. – Luu Hoang Bac Mar 06 '20 at 02:34
112

Simple:

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

Unless the array is a string:

foreach ($array as &$value) {
    $value = '-' . $value;
}
unset($value);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rohit Chopra
  • 2,791
  • 4
  • 28
  • 33
75

In this case, Rohit's answer is probably the best, but the PHP array functions can be very useful in more complex situations.

You can use array_walk() to perform a function on each element of an array altering the existing array. array_map() does almost the same thing, but it returns a new array instead of modifying the existing one, since it looks like you want to keep using the same array, you should use array_walk().

To work directly on the elements of the array with array_walk(), pass the items of the array by reference ( function(&$item) ).

Since php 5.3 you can use anonymous function in array_walk:

// PHP 5.3 and beyond!
array_walk($array, function(&$item) { $item *= -1; }); // or $item = '-'.$item;

Working example

If php 5.3 is a little too fancy pants for you, just use createfunction():

// If you don't have PHP 5.3
array_walk($array,create_function('&$it','$it *= -1;')); //or $it = '-'.$it;

Working example

Community
  • 1
  • 1
Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
  • How much slower is your method compared to Rohits? I like one-liner so it would be nice to know how much "loss of speed" it will cause. – mgutt Mar 09 '15 at 12:16
  • 2
    For simple numbers is probably faster a loop. Profile it:) In my case I needed to prefix strings before concatenating the whole array and the fastest solution was Array_walk followed by Implode. – CoffeDeveloper Apr 17 '15 at 23:42
  • Great solution. If you want to use previous declared var, add use($XXX) before "{ } : array_walk($rank, function(&$item) use($cpt) { if ($item >= $cpt) $item += 1; }); – Medhi Feb 18 '21 at 14:28
26

Something like this would do:

array_map(function($val) { return -$val;} , $array)
JRL
  • 76,767
  • 18
  • 98
  • 146
  • 3
    Note that this is PHP 5.3+ only (due to the anonymous function), and it returns a new array instead of modifying the existing array (so `print_r($array)` would show `$array` unchanged after the above. - If you assign the returned value to `$array` this'll get the job done nicely. – Peter Ajtai Oct 01 '11 at 04:15
12

You can replace "nothing" with a string. So to prefix an array of strings (not numbers as originally posted):

$prefixed_array = substr_replace($array, 'your prefix here', 0, 0);

That means, for each element of $array, take the (zero-length) string at offset 0, length 0 and replace it the prefix.

Reference: substr_replace

Dan Chadwick
  • 361
  • 3
  • 7
6
$array = [1, 2, 3, 4, 5];
$array=explode(",", ("-".implode(",-", $array)));
//now the $array is your required array
Sarwar Hasan
  • 1,561
  • 2
  • 17
  • 25
5

I had the same situation before.

Adding a prefix to each array value

function addPrefixToArray(array $array, string $prefix)
{
    return array_map(function ($arrayValues) use ($prefix) {
        return $prefix . $arrayValues;
    }, $array);
}

Adding a suffix to each array value

function addSuffixToArray(array $array, string $suffix)
{
    return array_map(function ($arrayValues) use ($suffix) {
        return $arrayValues . $suffix;
    }, $array);
}

Now the testing part:

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

print_r(addPrefixToArray($array, 'prefix'));

Result

Array ([0] => prefix1 [1] => prefix2 [2] => prefix3 [3] => prefix4 [4] => prefix5)

print_r(addSuffixToArray($array, 'suffix'));

Result

Array ([0] => 1suffix [1] => 2suffix [2] => 3suffix [3] => 4suffix [4] => 5suffix)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ManojKiran A
  • 5,896
  • 4
  • 30
  • 43
1

You can also do this since PHP 7.4:

$array = array_map(fn($item) => -$item, $array);

Live demo

Alfred Bez
  • 1,191
  • 1
  • 14
  • 31