Initialize an Associative Array with Key Names but Empty Values

旧城冷巷雨未停 提交于 2020-06-22 09:26:06

问题


I cannot find any examples, in books or on the web, describing how one would properly initialize an associative array by name only (with empty values) - unless, of course, this IS the proper way(?)

It just feels as though there is another more efficient way to do this:

config.php

class config {
    public static $database = array (
        'dbdriver' => '',
        'dbhost' => '',
        'dbname' => '',
        'dbuser' => '',
        'dbpass' => ''
    );
}

// Is this the right way to initialize an Associative Array with blank values?
// I know it works fine, but it just seems ... longer than necessary.

index.php

require config.php

config::$database['dbdriver'] = 'mysql';
config::$database['dbhost'] = 'localhost';
config::$database['dbname'] = 'test_database';
config::$database['dbuser'] = 'testing';
config::$database['dbpass'] = 'P@$$w0rd';

// This code is irrelevant, only to show that the above array NEEDS to have Key
// names, but Values that will be filled in by a user via a form, or whatever.

Any recommendations, suggestions, or direction would be appreciated. Thanks.


回答1:


What you have is the most clear option.

But you could shorten it using array_fill_keys, like this:

$database = array_fill_keys(
  array('dbdriver', 'dbhost', 'dbname', 'dbuser', 'dbpass'), '');

But if the user has to fill the values anyway, you can just leave the array empty, and just provide the example code in index.php. The keys will automatically be added when you assign a value.




回答2:


First file:

class config {
    public static $database = array();
}

Other file:

config::$database = array(
    'driver' => 'mysql',
    'dbhost' => 'localhost',
    'dbname' => 'test_database',
    'dbuser' => 'testing',
    'dbpass' => 'P@$$w0rd'
);


来源:https://stackoverflow.com/questions/12880026/initialize-an-associative-array-with-key-names-but-empty-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!