开发者

How to the values of an array to populate the keys of another array?

开发者 https://www.devze.com 2022-12-28 11:49 出处:网络
I have an array of field names. I would like to use tho开发者_运维技巧se to populate the keys of another array, which will have empty values as default. Is there a single command I can do this with?As

I have an array of field names. I would like to use tho开发者_运维技巧se to populate the keys of another array, which will have empty values as default. Is there a single command I can do this with?


As of PHP 5.2.0 you can also use array_fill_keys

array_fill_keys( array('foo', 'bar', 'baz'), NULL);

which will give

Array
(
    [foo] => 
    [bar] => 
    [baz] => 
)


Try the array_combine and array_fill functions:

array_combine($arrayOfKeys, array_fill(0, count($arrayOfKeys), null))

Or, as array_fill is only available since PHP 4.2, try array_pad instead:

array_combine($arrayOfKeys, array_pad(array(), count($arrayOfKeys), null))


If I understand your question, you need array_combine()

0

精彩评论

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

关注公众号