0

I have an array like

$arr = [
  'foo' => [
    'bar' => [
      1
    ],
    'baz' => [
      1
    ]
  ]
]

And another one

$path = ['foo', 'bar', 0];

I need to modify the value from $arr using $path. I need the solution to be very simple, I tried something like

$arr...$path = 2;
$arr[...$path] = 2;

After the modification $arr should look like

$arr = [
  'foo' => [
    'bar' => [
      2
    ],
    'baz' => [
      1
    ]
  ]
]

But I got errors. I don't always know how many levels the array will have.

1
  • its confusing. show the result array you need to recieve from $arr = [ 'foo' => [ 'bar' => [ 1 ] ] ] and $path = ['foo', 'bar']; Commented Jul 25, 2015 at 8:32

3 Answers 3

4

Your path is incorrect - for $arr[$path] = 2; you need

$path = ['foo', 'bar', 0];

$p = &$arr;
foreach($path as $step) 
   $p = &$p[$step];
echo $p . "\n";
$p = 2;
print_r($arr);

Or with

$path = ['foo', 'bar'];

$p = &$arr;
foreach($path as $step) 
   $p = &$p[$step];
echo $p[0] . "\n";
$p[0] = 2;
print_r($arr);
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$link =& $arr;
foreach ($path AS $p) 
{
    $link =& $link[$p];
}
$link[0]++;

Comments

-1
$arr[$path[0]][$path[1]] ='XXX'

1 Comment

That is not very helpful.

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.