Page 1 of 1

Append string to every element in an array

Posted: Mon Aug 16, 2004 7:16 pm
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?

Posted: Mon Aug 16, 2004 7:47 pm
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.