1

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?

10
  • Have you tried anything? Commented Mar 15, 2017 at 8:22
  • why do you want to do that? i'm sure there will be better approaches than that; Commented Mar 15, 2017 at 8:23
  • I tried using array push, but that completely deletes the node and makes a new array in it's place. Commented Mar 15, 2017 at 8:23
  • is the format of fetching array index the same or varying.? Eg: for 5,6,2,8 array index will be 2,3,4,5. Commented Mar 15, 2017 at 8:23
  • No, for 5,6,2,8 the array index will also be 5,6,2,8. Basically I'll get the array index from the other array Commented Mar 15, 2017 at 8:24

1 Answer 1

4

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

2 Comments

Also, could you please explain what the & does? Is it a pointer reference?
here is the & reference manual php.net/manual/en/language.references.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.