Emilio Rodrigues
Emilio Rodrigues

Reputation: 263

Set array element using another array containing path

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

Answers (3)

M0rtiis
M0rtiis

Reputation: 3774

Try this:

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

Upvotes: 1

splash58
splash58

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

JOE LEE
JOE LEE

Reputation: 1058

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

Upvotes: -1

Related Questions