Reputation: 263
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.
Upvotes: 0
Views: 49
Reputation: 3774
Try this:
$link =& $arr;
foreach ($path AS $p)
{
$link =& $link[$p];
}
$link[0]++;
Upvotes: 1
Reputation: 26143
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);
Upvotes: 4