0

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?

3 Answers 3

2

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] => 
)
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

only available since PHP 4.2 - Released: 22 April 2002 de3.php.net/releases ;)
@Gordon: It’s sad, but there are servers out there that still have a lower PHP version running.
1

If I understand your question, you need array_combine()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.