Like Jon suggested (and being asking feedback for in chat), a reference/variable alias is helpful here to traverse the dynamic stack of keys. So the only thing needed is to iterate over all subkeys and finally set the value:
$rv = &$target;
foreach(explode('.', $key) as $pk)
{
$rv = &$rv[$pk];
}
$rv = $value;
unset($rv);
The reference makes it possible to use a stack instead of recursion which is generally more lean. Additionally this code prevents to overwrite existing elements in the $target
array. Full example:
$key = "Main.Sub.SubOfSub";
$target = array('Main' => array('Sub2' => 'Test'));
$value = "SuperData";
$rv = &$target;
foreach(explode('.', $key) as $pk)
{
$rv = &$rv[$pk];
}
$rv = $value;
unset($rv);
var_dump($target);
Output:
array(1) {
["Main"]=>
array(2) {
["Sub2"]=>
string(4) "Test"
["Sub"]=>
array(1) {
["SubOfSub"]=>
string(9) "SuperData"
}
}
}
Demo
Related Question(s):