Php: Concatenate string into all array items
Alternative example using array_map
: http://php.net/manual/en/function.array-map.php
PHP:
$colors = array('red','green','blue');
$result = array_map(function($color) {
return "color-$color";
}, $colors);
Output ($result
):
array(
'color-red',
'color-green',
'color-blue'
)
The method array_walk will let you 'visit' each item in the array with a callback. With php 5.3 you can even use anonymous functions
Pre PHP 5.3 version:
function carPrefix(&$value,$key) {
$value="car-$value";
}
array_walk($colors,"carPrefix");
print_r($colors);
Newer anonymous function version:
array_walk($colors, function (&$value, $key) {
$value="car-$value";
});
print_r($colors);