Fastest way to add prefix to array keys?

后端 未结 9 1475
迷失自我
迷失自我 2020-11-28 14:29

What is the fastest way to add string prefixes to array keys?

Input

$array = array(
 \'1\' => \'val1\',
 \'2\' => \'val2\',
);
<
9条回答
  •  一生所求
    2020-11-28 14:44

    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.

提交回复
热议问题