try it with:
$target = array();
$value = array();
$path = array('apple', 'orange', 'tomato');
$rv = &$target;
foreach($path as $pk)
{
$rv = &$rv[$pk];
}
$rv = $value;
unset($rv);
print_r($target);
output:
Array
(
[apple] => Array
(
[orange] => Array
(
[tomato] => Array
(
)
)
)
)
Update 1: Explaination
Here I am using reference/variable alias to traverse the dynamic stack of keys. 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.
For more detail on references have a look at Reference Explained
$target = array(); //target array where we will store required out put
$value = array(); //last value i.e. blank array
$path = array('apple', 'orange', 'tomato'); //current array
$rv = &$target; //assign address of $target to $rv (reference variable)
foreach($path as $pk)
{
$rv = &$rv[$pk]; // Unused reference [ex. $rv['apple'] then $rv['apple']['orange'] .. so on ] - actually assigned to $target by reference
print_r($target);
echo '-----------------<br />';
}
$rv = $value; //here $rv have unused refernce of value tomato so finally assigned a blank array to key tomoto
//
unset($rv); // Array copy is now unaffected by above reference
echo "final array<br />";
print_r($target);
output:
Array
(
[apple] =>
)
-----------------
Array
(
[apple] => Array
(
[orange] =>
)
)
-----------------
Array
(
[apple] => Array
(
[orange] => Array
(
[tomato] =>
)
)
)
-----------------
final array
Array
(
[apple] => Array
(
[orange] => Array
(
[tomato] => Array
(
)
)
)
)
In output of explaination you can trace the value of $target in foreach loop