0

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!

TLammar
  • 3
  • 1
  • I can't imaging the situation where you'd want to do this ! – Harshal Patil Apr 14 '14 at 15:04
  • in a database are different links stored. a link has a parent based on id's. link1 => id = 1, parent = 0_ link2 => id = 2, parent = 0_1_. i'm trying to get $foo[0][1]... => $foo2 = (0,1,...) – TLammar Apr 14 '14 at 15:05

1 Answers1

2

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);

Demo


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;

Demo

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150