Jay Ghosh
Jay Ghosh

Reputation: 682

PHP get sub array dynamically

I have an array (which will be dynamically populated) called $currentTree

Now I want to use this array to iterate over and another array called $tree

So, for example

$currentTree = array(5, 6, 2, 8);

becomes

$tree[5][6][2][8] = "hello world"; //the values of $currentTree is used to get the appropriate child node of array $tree

Is there any predefined PHP function I can use to achieve this?

Upvotes: 1

Views: 432

Answers (1)

LF-DevJourney
LF-DevJourney

Reputation: 28524

use reference, here is the live demo

<?php
$currentTree = array(-1, 5, 6, 2, 8);
$ref = &$tree;
    while($v = next($currentTree))
    {
      $ref = &$ref[$v];
    }
    $ref = "hello world";

    print_r($tree);

Upvotes: 4

Related Questions