What is the fastest way to add string prefixes to array keys?
Input
$array = array(
\'1\' => \'val1\',
\'2\' => \'val2\',
);
<
I figured out one-line solution:
array_walk($array, create_function('$value, &$key', '$key = "prefix" . $key;'));
Could do this in one long line I presume:
$array = array_combine(
array_map(function($k){ return 'prefix'.$k; }, array_keys($array)),
$array
);
Or for versions of PHP prior to 5.3:
$array = array_combine(
array_map(create_function('$k', 'return "prefix".$k;'), array_keys($array)),
$array
);
There's probably dozens of ways to do this though:
foreach ($array as $k => $v)
{
$array['prefix_'.$k] = $v;
unset($array[$k]);
}
function keyprefix($keyprefix, Array $array) {
foreach($array as $k=>$v){
$array[$keyprefix.$k] = $v;
unset($array[$k]);
}
return $array;
}
Using array_flip
will not preserve empty or null values.
Additional code could be added in the unlikely event that the prefixed key already exists.