Dr.Kameleon
Dr.Kameleon

Reputation: 22810

Set value to nested array subelement

OK, so here's what I'm trying to do :

How's is that doable?

Example

Let's say : putValueAtPosition($arr, "someValue",array(3,5,8)); will set $arr[3][5][8] = "someValue" and return the resulting array (the full set).

Any ideas/input is welcome?


P.S. I'm working on a totally different problem (but with the same core concept) and not even in PHP (doesn't matter though - PHP's clear enough to get the point through! ;-) ), and I've tried all sorts of over-complicated things with recursive functions and passing by reference (or not), my head is about to explode...

Upvotes: 0

Views: 93

Answers (1)

Steve
Steve

Reputation: 20459

function putValueAtPosition(&$arr, $val , $path){
    $marker=&$arr;
    foreach($path as $p){
        $marker=&$marker[$p];
    }
    $marker=$val;
}


$test=array(
    1=>array(
        1=>array(
            1=>'cat',
            2=>'hello'
        ),
        2=>'hello'
    ),
    2=>'hello'

);

print_r($test);
putValueAtPosition($test, 'changed', array(1,1,1));
print_r($test);

Upvotes: 3

Related Questions