Marty Wallace
Marty Wallace

Reputation: 35734

Fill an associative array with values to initialise

I have the following array:

array(
    'elem1', 'elem2', 'elem3'
);

I want to have the following:

array(
    'elem1' => 0,
    'elem2' => 0,
    'elem3' => 0
);

is this possible with array_fill? I cant see that it is.

If not, is there a way to do this without iterating over the array?

Upvotes: 5

Views: 2130

Answers (1)

Bhuvan Rikka
Bhuvan Rikka

Reputation: 2703

Yup.. Try this

<?php
$keys = array('elem1', 'elem2', 'elem3');
$a = array_fill_keys($keys, 0);
print_r($a);
?>

Output:

array(
    'elem1' => 0,
    'elem2' => 0,
    'elem3' => 0
);

Upvotes: 11

Related Questions