Kline
Kline

Reputation: 47

PHP setting array value through dynamic path

I am trying here to set the vale of the first child element of $map. I need to do this by referencing the path of the array i.e [0]['child'].

The function returns the path value ok if set but I am having trouble changing the value of that of that element. So in this case I want $map[0]['child'] to equal "new".

function getArrayPath($arr,$path) {

    foreach($path as $item){
    $arr = $arr[$item];
    }

    return $arr;
}


$map='[{"child":""},{"child":""},{"child":""}]';

$map=json_decode($map,true);

$path = array("0","child");

$target = getArrayPath($map,$path);

if($target==""){
$target="new";
}

var_dump($map);

Upvotes: 0

Views: 252

Answers (1)

kero
kero

Reputation: 10638

You can solve this by using references:

function &getArrayPath(&$arr,$path) {
//       ^--return     ^--receive
//          reference     reference
    foreach($path as $item){
        $arr =& $arr[$item];
//            ^--assign reference
    }
    return $arr;
}


$map = json_decode('[{"child":"1"},{"child":"2"},{"child":"3"}]', true);
$path = array("0","child");

$target =& getArrayPath($map,$path);
//       ^--assign reference

as you can see in this demo (your code slightly changed).

Since PHP does not assign/return by reference as default, you always need to explicitly do that by adding the & operator.

Upvotes: 3

Related Questions