Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill an associative array with values to initialise

Tags:

php

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?

like image 464
Marty Wallace Avatar asked Dec 21 '12 13:12

Marty Wallace


People also ask

What is associative array with example?

Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice.

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

How do you find the associative value of an array?

You can use the PHP array_values() function to get all the values of an associative array.


1 Answers

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
);
like image 67
Bhuvan Rikka Avatar answered Oct 25 '22 06:10

Bhuvan Rikka