user151841
user151841

Reputation: 18046

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

I have an array of field names. I would like to use those to populate the keys of another array, which will have empty values as default. Is there a single command I can do this with?

Upvotes: 0

Views: 145

Answers (3)

Gordon
Gordon

Reputation: 316939

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] => 
)

Upvotes: 2

Gumbo
Gumbo

Reputation: 655129

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))

Upvotes: 2

Matteo Riva
Matteo Riva

Reputation: 25060

If I understand your question, you need array_combine()

Upvotes: 1

Related Questions