Reputation: 13
I have a function called get_config()
and an array called $config
.
I call the function by using get_config('site.name')
and am looking for a way to return the value of $config
so for this example, the function should return $config['site']['name']
.
I'm nearly pulling my hair out - trying not to use eval()
! Any ideas?
EDIT: So far I have:
function get_config($item)
{
global $config;
$item_config = '';
$item_path = '';
foreach(explode('.', $item) as $item_part)
{
$item_path .= $item."][";
$item = $config.{rtrim($item_path, "][")};
}
return $item;
}
Upvotes: 1
Views: 83
Reputation: 157927
This should work:
function get_config($config, $string) {
$keys = explode('.', $string);
$current = $config;
foreach($keys as $key) {
if(!is_array($current) || !array_key_exists($key, $current)) {
throw new Exception('index ' . $string . ' was not found');
}
$current = $current[$key];
}
return $current;
}
Upvotes: 1
Reputation: 1
Inside your get_config function, you can parse the string using explode function in php
function get_config($data){
$pieces = explode(".", $data);
return $config[$pieces[0]][$pieces[1]];
}
Upvotes: 0
Reputation: 3494
you could try something like...
function get_config($item)
{
global $config;
return $config[{str_replace('.','][',$item)}];
}
Upvotes: 0