开发者

Modifing associative array keys & values (yes keys too). array_walk or foreach or something else

开发者 https://www.devze.com 2023-03-10 22:04 出处:网络
I am trying to modify an associative array eg. array( \'key1\' => \'val1\', \'key2\' => \'val2\', \'key3\' => \'val3\'

I am trying to modify an associative array eg.

array(
    'key1' => 'val1',
    'key2' => 'val2',
    'key3' => 'val3'
)

to something like

array(
    ':key1' => 'val1xx',
    ':key2' => 'val2xx',
    ':key3' => 'val3xx'
  // ^ colen        
)

You may recognize I am trying to convert it into something I can use in PDOStatement::execute(). I dont currently need to modify the value, in this case. But will like to know just for knowledge

What can I use to do that? I am thinking foreach can do 开发者_运维问答most things, but do functions like array_map or array_walk provide any benefits? Like performance? Or just looks different


There exists a big performance gap between the foreach and the array_map method. The fastest is the foreach construct. This construct can be five to six times as fast as an anonymous function, at least when there is not much to do within the loop. In most scenarios, the time it takes to iterate over the array is negligible compared to the time spend in the loop or anonymous function. So this performance difference does not really matter.For more information see link here.


$result = array();
foreach ($array as $key => $value)
  $result[":$key"] = "{$value}xx";


Thariama's answer points to the performance gap between the for loop and array_map. It should also be pointed that there is no loop-free manner for modifying the keys in an array. You can modify the values in different loop-free ways (including array_map and array_walk) but not the keys.

0

精彩评论

暂无评论...
验证码 换一张
取 消