-2

I have a config.php file that looks like this

return array(
"array1"=>
    array(
      "array2"=>"value"
    )
);

How can I dynamically extract array2 value using a function like this?

function getConfigValue(?)
{
    $config = include("config.php");
    return $config....  
}
user3379466
  • 2,637
  • 2
  • 12
  • 11

1 Answers1

5
$path  = 'array1.array2';
$value = array_reduce(
    explode('.', $path),
    function (array $value, $key) { return $value[$key]; },
    $config
);
deceze
  • 471,072
  • 76
  • 664
  • 811
  • Be aware that this method throws an error if you access a key which is not in the array. You could improve the function by adding `if(isset($value[$key]) === false) return null;` to the beginning of the anonymous function. So you get `NULL` instead of a warning message. – TiMESPLiNTER Jul 04 '14 at 12:04
  • actually i've used a particular php framework which also utilizes this kind of style in calling configs. +1 brilliant answer –  Jul 04 '14 at 12:06
  • @TiMESPLiNTER Yes, this could certainly use more obvious error messages. However, the `array` type hint will let your program error out completely, no need for `isset`. If you don't want hard errors but want to soft-fail instead, a manual check may be better. Depends on your priorities and design goals here. – deceze Jul 04 '14 at 12:09