add list of key's to an multidimensional array
-
26-12-2019 - |
Question
I'll try to be brief, yet clear. for example:
$foo['test'] = array();
$foo2('test1','test2','test3','test4');
is it possible to create some kind of a loop to get this multidimensional array?:
$foo['test']['test1']['test2']['test3']['test4'] = ...;
You don't know in advance how long the $foo2 array will be. I hope my question is clear and not to stopid to ask.
Any help is welcome! thanks in advance!
Solution
I can't think of a valid use-case for this. But you can do this with references (modified version of this answer)
$foo['test'] = array();
$foo2 = array('test1','test2','test3','test4');
$result = array();
$temp = &$result;
foreach($foo2 as $value) {
$temp[$value] = array();
$temp = &$temp[$value];
}
unset($temp);
$foo['test'] = $result;
var_dump($foo);
A stupid and dumb solution using eval()
. This should not be used. I'm posting it just for the fun of it ;)
$foo2 = array('test1','test2','test3','test4');
eval("\$res['".join("']['",$foo2)."']=[];");
$foo['test'] = $res;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow