1

I have an array of indexes and a value to insert.

$indexes = [0,1,4];
$value_to_insert = 820;
$array_to_fill = [];

How can i use the indexes array like this to insert a value:

$array_to_fill[$indexes] = 820;

To produce a nested array of this style:

$array_tree = [
            "0" => [
                "1" => [
                    "4" => 820
                ]
            ]
        ]

i tried using pointers to maybe save the location of the array but that only saves a chunk of the array not the position. I have spent too many hours on this and help would be very much appreciated.

1 Answer 1

2

You can create a "pointer" with & and update it to point to the latest level you create :

$indexes = [0,1,4];
$value_to_insert = 820;
$array_to_fill = [];

$current_root = &$array_to_fill ; // pointer to the root of the array
foreach($indexes as $i)
{
    $current_root[$i] = array(); // create a new sub-array
    $current_root = &$current_root[$i] ; // move the pointer to this new level
}
$current_root = $value_to_insert ; // finally insert the value into the last level
unset($current_root);

print_r($array_to_fill);
Sign up to request clarification or add additional context in comments.

Comments

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.