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.
Declaring and initializing Associative Array: An associative array can be declared in bash by using the declare keyword and the array elements can be initialized at the time of array declaration or after declaring the array variable.
Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
The $_POST is an associative array of variables. These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.
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.
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' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With