1

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;
}
3
  • 1
    show us what you have so far Commented Feb 8, 2014 at 19:30
  • Like explode(" ") ? Commented Feb 8, 2014 at 19:32
  • Not really. I need to then use the split string to access an multi-dimensional array - which I can't seem to do with explode(). Commented Feb 8, 2014 at 19:34

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! It works. Thank you! I will accept your answer as soon as I can :D
0

you could try something like...

function get_config($item)
{
      global $config;
      return $config[{str_replace('.','][',$item)}];
}

Comments

0

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]];

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.