views:

72

answers:

3

Hi friends,

I have one array as

$tmpArr =  array('A', 'B', 'C');

I want to process this array and want new array as

$tmpArr[A][B][C] = C

I.e last element becomes the value of final array.

Can anyone suggest the solution? Please help. Thanks in advance

+1  A: 
$tmpArr[$tmpArr[0]][$tmpArr[1]][$tmpArr[2]] = $tmpArr[2];

Is that what you want?

Tokk
yes, exactly. But I want it dynamic I.e number of elements are not fixed. it may vary.
Nilesh
+2  A: 

Iterate the array of keys and use a reference for the end of the chain:

$arr = array();
$ref = &$arr;
foreach ($tmpArr as $key) {
    $ref[$key] = array();
    $ref = &$ref[$key];
}
$ref = $key;
$tmpArr = $arr;
Gumbo
You beat me to it. I had almost exactly the same thing (the only difference is the variable names)... +1
ircmaxell
+1  A: 
$tmpArr =  array('A', 'B', 'C');
$array = array();
foreach (array_reverse($tmpArr) as $arr)
      $array = array($arr => $array);

Output:

Array
(
    [A] => Array
        (
            [B] => Array
                (
                    [C] => Array
                        (
                        )

                )

        )

)
Russell Dias