Initialize an Associative Array with Key Names but Empty Values

PhpArraysInitializationAssociative

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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'
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNYCBillyView Question on Stackoverflow
Solution 1 - PhpGolezTrolView Answer on Stackoverflow
Solution 2 - PhpSethView Answer on Stackoverflow