I have this PHP snippet:
<?php
$colors = array('red','green','blue');
foreach ($colors as &$item)
{
$item = 'color-'.$item;
}
print_r($colors);
?>
Output:
Array
(
[0] => color-red
[1] => color-green
[2] => color-blue
)
Is it simpler solution ?
(some array php function like that array_insert_before_all_items($colors,"color-")
)?
Thanks
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);
Try this:
$colors = array('red','green','blue');
function prefix_car( &$item ) {
$item = "car-{$item}";
}
array_walk( $colors, 'prefix_car');
It should work the same way you're doing it, albeit somewhat more sternly; array_walk gives an inkling more flexibility than manually looping.
$colors = array('red','green','blue');
$prefix = "car-";
$color_flat = $prefix . implode("::" . $prefix,$colors);
$colors = explode("::",$color_flat);
print_r($colors);
For older versions of php this should work
foreach ($colors as $key => $value) {
$colors[$key] = 'car-'.$value; //concatinate your existing array with new one
}
print_r($sbosId);
Result :
Array
(
[0] => car-red
[1] => car-green
[2] => car-blue
)
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'
)