Php: combine string into all elements of an array

I have this PHP fragment:

<?php $colors = array('red','green','blue'); foreach ($colors as &$item) { $item = 'color-'.$item; } print_r($colors); ?> 

Exit:

 Array ( [0] => color-red [1] => color-green [2] => color-blue ) 

Is this a simpler solution?

(some php array function like array_insert_before_all_items($colors,"color-") )?

thanks

+7
source share
5 answers

The array_walk method will allow you to β€œvisit” each element of the array with a callback. With php 5.3 you can even use anonymous functions

Version for PHP 5.3:

 function carPrefix(&$value,$key) { $value="car-$value"; } array_walk($colors,"carPrefix"); print_r($colors); 

New version of anonymous function:

 array_walk($colors, function (&$value, $key) { $value="car-$value"; }); print_r($colors); 
+12
source

For older php versions 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 ) 
+2
source

Try the following:

 $colors = array('red','green','blue'); function prefix_car( &$item ) { $item = "car-{$item}"; } array_walk( $colors, 'prefix_car'); 

It should work just like you do, albeit a little more strictly; array_walk gives you more flexibility than manual binding.

+1
source
 $colors = array('red','green','blue'); $prefix = "car-"; $color_flat = $prefix . implode("::" . $prefix,$colors); $colors = explode("::",$color_flat); print_r($colors); 
0
source

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' ) 
0
source

All Articles