Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php: Concatenate string into all array items

Tags:

arrays

php

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

like image 244
kubedan Avatar asked Mar 24 '12 07:03

kubedan


People also ask

How do you concatenate all elements in an array?

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.

How do you implode an array?

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.

How do you join strings in PHP?

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.


3 Answers

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);
like image 76
Adam Avatar answered Nov 09 '22 23:11

Adam


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'
)
like image 24
adamj Avatar answered Nov 10 '22 00:11

adamj


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
)
like image 34
Bunny Avatar answered Nov 09 '22 23:11

Bunny