I have a string of delimiter-separated values, and need to perform some_func on each of the values in the string. What is the most compact/elegant way to accomplish this? Here is the code I would currently use:
$delim = ',';
$source_array = explode($delim, $source_string);
$destination_array = array();
foreach ($source_array as $val) {
$destination_array[] = some_function($val);
}
$destination_string = implode($delim, $destination_array);
Ordering is not important, but would be nice to preserve.
Thanks!
You're looking for array_map
:
$delim = ',';
$source_array = explode($delim, $source_string);
$destination_array = array_map('some_function', source_array)
$destination_string = implode($delim, $destination_array);
Try regular expressions/ REGEX. Or if the algorithm is heavy make a script in Perl to handle all this and call it from PHP. It will make things easier.
Well, i know, someone will tell you Python or another scripting language, but thats my 2 cents.
You could use array_walk
. This way you can apply a function to each entry in the array. So your code would look like this:
$delim = ',';
$parts = explode($delim, $source_string);
array_walk($parts, 'some_function');
$destination_string = implode($delim, $parts);
Compared to array_map
, it won't generate a new array but work on the existing array... but that's only going to be significant if you work with huge arrays (think memory). And of course it won't work if you have to access other array values in some_function
...