Add a prefix to each item of a PHP array
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
.
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
Simple:
foreach ($array as &$value) {
$value *= (-1);
}
unset($value);
Unless the array is a string:
foreach ($array as &$value) {
$value = '-' . $value;
}
unset($value);