Add a prefix to each item of a PHP array

MBL picture MBL · Oct 1, 2011 · Viewed 77.1k times · Source

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?

Answer

Dávid Horváth picture Dávid Horváth · Jan 23, 2015

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.