3

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

2
  • this does not make sense Commented Sep 27, 2010 at 13:10
  • id on't think this makes any sense, too, but if you wan't help, please provide a little more information - what schould happen is the input inrray has more/less than 3 elements? what have you tried till now? why do yau have to do this transformation and can't do it like you need when you're creating the array? Commented Sep 27, 2010 at 13:14

3 Answers 3

10

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;
Sign up to request clarification or add additional context in comments.

1 Comment

You beat me to it. I had almost exactly the same thing (the only difference is the variable names)... +1
10
$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
                        (
                        )

                )

        )

)

Comments

2
$tmpArr[$tmpArr[0]][$tmpArr[1]][$tmpArr[2]] = $tmpArr[2];

Is that what you want?

1 Comment

yes, exactly. But I want it dynamic I.e number of elements are not fixed. it may vary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.