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 join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
If we have an array of elements, we can use the implode() function to join them all to form one string. We basically join array elements with a string. Just like join() function , implode() function also returns a string formed from the elements of an array.
The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (' . = '), which appends the argument on the right side to the argument on the left side.
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);
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'
)
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With