Here's one way you can do it with a recursive function. This is my personal favourite because it has very good readability.
function nest(array $keys, $value) {
if (count($keys) === 0)
return $value;
else
return [$keys[0] => nest(array_slice($keys, 1), $value)];
}
$result = nest(['key1', 'key2', 'key3'], 'foo');
print_r($result);
// Array
// (
// [key1] => Array
// (
// [key2] => Array
// (
// [key3] => foo
// )
// )
// )
Or another way you can do it using array_reduce
. This way is also quite nice but there's a little added complexity here because the array of keys has to be reversed first.
function nest(array $keys, $value) {
return array_reduce(array_reverse($keys), function($acc, $key) {
return [$key => $acc];
}, $value);
}
$result = nest(['key1', 'key2', 'key3'], 'foo');
print_r($result);
// Array
// (
// [key1] => Array
// (
// [key2] => Array
// (
// [key3] => foo
// )
// )
// )
Both solutions work for any number of keys. Even if $keys
is an empty array
nest([], 'foo'); //=> 'foo'