Append string to every element in an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Append string to every element in an array

Post by hawleyjr »

I have an array:

Code: Select all

<?php
$a_name = ('james','mike','keith','dan'.......);
?>
Is there away to append a string to the beginning of each element without looping through each value?

I can do it like this I just have a dozen or so arrays and I don't want a dozen or so more loops.

Code: Select all

<?php
foreach($a_name as $val){
 $a_name[] = 'Before '.$val;
}
?>
Any suggestions?
User avatar
protokol
Forum Contributor
Posts: 353
Joined: Fri Jun 21, 2002 7:00 pm
Location: Cleveland, OH
Contact:

Post by protokol »

There are many solutions to this, but here is an example of one of them:

Code: Select all

<?php
 // prefix each value in the array with this
$prefix = 'Before ';
 
// input array
$a_name = array('james','mike','keith','dan');

// Map an anonymous function across each value in the array which prefixes each value
$a_name =& array_map(create_function('$arr_val', 'return '''.$prefix.'''.$arr_val;'), $a_name);

// If you don't want to create a copy, then use this to manipulate the values
// referenced in the array
array_walk($a_name, create_function('&$arr_val', '$arr_val = '''.$prefix.'''.$arr_val;'));
?>
Hopefully it's obvious, but only use 1 of array_map() or array_walk(). Take your pick.
Post Reply