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

时间:2012-10-14 06:58:45

标签: 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.

的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.

任何建议,建议或指示都将不胜感激。感谢。

2 个答案:

答案 0 :(得分:51)

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

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

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

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

答案 1 :(得分:1)

第一档:

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

其他档案:

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