Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create array in PHP with strings from another array as position names?

Tags:

arrays

php

Basically what I'm trying to do is create an array that has strings for their position names, such as:

$types = [
    "Methods" => array(),
    "Systems" => array(),
    "Equipment" => array()
]

This is what var_dump($types) results in:

array(3) { ["Methods"]=> array(0) { } ["Systems"]=> array(0) { } ["Equipment"]=> array(0) { } } 

However, instead of declaring $types like this, I want to have an array $list...

$list = ['Foo', 'Bar', 'Baz', ...];

...that generates an array $types...

$types = ["Foo" => array(), "Bar" => array(),"Baz" => array(), ...]

Is it possible? I have tried doing array_push($types, $list) but that just copies the the string array into the last position of $types

like image 966
Leonardo Freitas Avatar asked Aug 03 '26 09:08

Leonardo Freitas


1 Answers

Use array_fill_keys function

$types = array_fill_keys($list, []);
like image 60
splash58 Avatar answered Aug 05 '26 23:08

splash58



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!