Return value from associative array using config function

Get the value of given situation:
Let’s say I have an associative array:

$config = [
  'foo' => 'bar',
  'baz' => [
    'name' => 'MyFirstApp',
    'env' => 'production',
  ],
  'database' => [
    'host' => 'localhost',
    'dbname' => 'test',
    'username' => 'root',
    'password' => 'password'
  ],
  'bar' => [
    'baz' => [
      'foo' => 1200
    ]
  ]
];

Now I want to make a config function which will return exact value when I try to pass baz.env parameter in that function.
And if I pass foo it would return bar
And if I pass bar.baz.foo it would return 1200

Can you tell me how can acheive this thing?

I treid it like below, but I need to make it dynamic:

function config($str) {
  global $config;

  $str_parts = explode('.', $str);
  if (array_key_exists($str[0], $config)) {
    return $config[$str[0]];
  }
}