I have an array to store the configuration like this
$config = array (
'db' => array(
'db1' => array(
'dbname' => 'mydatabase',
'user' => 'myusername',
'pass' => 'mypassword',
'host' => 'myhost'
)
),
'url' => array(
'homeUrl' => 'http://www.example.com'
)
)
And I’m writing a function to retrieve the data from the array by passing in a string like db.db1.dbname and it supposes to give me 'mydatabase'
I tried to explode the string into an array in order to get the keys, db, db1, and dbname. but after that, I got kinda stuck on how exactly I’m supposed to use them like $config -> db -> db1 -> dbname or $config['db']['db1']['dbname'] in order to get 'mydatabase'.
Ideally, say I have the function named read($arg, $array), and I would like to retrieve results like this
read('db.db1.dbname', $config), returns 'mydatabase'
read('url.homeUrl', $config), returns 'http://www.example.com'
Since I don’t know how many keys are contained in the string, I need this to be more dynamic.
Thanks in advance
I’m really wondering why you would want to do this, but here it goes:
Note that you would have to check whether the keys exists and throw an error or exception if that’s not the case.
Instead of using the function is there a reason why you cannot do: