DiscreteTomatoes
DiscreteTomatoes

Reputation: 789

PHP use Array of indexes as Array index

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.

Upvotes: 1

Views: 87

Answers (1)

Joffrey Schmitz
Joffrey Schmitz

Reputation: 2438

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);

Upvotes: 2

Related Questions