What is the fastest way to add string prefixes to array keys?
Input
$array = array(
\'1\' => \'val1\',
\'2\' => \'val2\',
);
<
If you don't want to use for loop you can do:
// function called by array_walk to change the $value in $key=>$value.
function myfunction(&$value,$key) {
$value="prefix$value";
}
$keys = array_keys($array); // extract just the keys.
array_walk($keys,"myfunction"); // modify each key by adding a prefix.
$a = array_combine($keys,array_values($array)); // combine new keys with old values.
I don't think this will be more efficient than the for
loop. I guess array_walk will internally use a loop and there is also the function call overhead here.