How can the function getConfigAttribute() be utilized to simplify access to specific attributes within a multidimensional configuration array in PHP?
When dealing with a multidimensional configuration array in PHP, it can be cumbersome to access specific attributes deep within the array. To simplify this process, you can create a function like getConfigAttribute() that takes the configuration array, a key path, and a default value as parameters. This function will traverse the array using the key path and return the value if found, or the default value if not found.
function getConfigAttribute($config, $keyPath, $default = null) {
$keys = explode('.', $keyPath);
$value = $config;
foreach ($keys as $key) {
if (isset($value[$key])) {
$value = $value[$key];
} else {
return $default;
}
}
return $value;
}
// Example usage
$config = [
'database' => [
'host' => 'localhost',
'username' => 'root',
'password' => 'password123'
]
];
$host = getConfigAttribute($config, 'database.host', 'default_host');
echo $host; // Output: localhost
$username = getConfigAttribute($config, 'database.user', 'default_user');
echo $username; // Output: default_user