0

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);
3
  • Well you are checking if($target == ""), then setting $target to "new". Commented Nov 12, 2014 at 13:40
  • This code makes no sense what so ever.Please explain what you are trying to do Commented Nov 12, 2014 at 13:43
  • You are assigning an element of the array to $target and changing value of $target. This won't change the array. You need to write a function that takes an array reference and changes the value of the given path. Commented Nov 12, 2014 at 13:45

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That's great thank you, a bit confusing though it will take some time to grasp this properly.
@Kline It took me some time to get it working as well. References aren't that much used in PHP and certainly not common. Maybe you can solve this another way, eg. having a setArrayPath($map, $path, $value) or changing the design altogether
Maybe a few too many references (I was able to simplify a bit), but excellent answer. Got me going in the right direction to solve my problem!

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.