使用键名但空值初始化关联数组

NYC*_*lly 53 php arrays initialization associative

我无法在书籍或网络上找到任何示例,描述如何通过名称正确初始化关联数组(使用空值) - 当然,除非这是正确的方式(?)

感觉好像还有另一种更有效的方法:

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.
Run Code Online (Sandbox Code Playgroud)

的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.
Run Code Online (Sandbox Code Playgroud)

任何建议,建议或方向将不胜感激.谢谢.

Gol*_*rol 54

你拥有的是最明确的选择.

但你可以使用array_fill_keys缩短它,如下所示:

$database = array_fill_keys(
  array('dbdriver', 'dbhost', 'dbname', 'dbuser', 'dbpass'), '');
Run Code Online (Sandbox Code Playgroud)

但是如果用户必须填写值,你可以将数组留空,只需在index.php中提供示例代码即可.分配值时,将自动添加键.