10

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

6 Answers 6

18

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

If you have no intention of using $key, don't declare it.
6

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

Comments

3

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 ) 

Comments

1

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.

Comments

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

Comments

0
$colors = array('red','green','blue'); $colors = substr_replace($colors, 'color-', 0, 0); print_r($colors); 

1 Comment

Please add a little bit of explanation of your code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.