PHP: Set value of nested array using variable as key
Easiest way to do this would be using set method from this library:
Arr::set($array, 'a.b.c', 'new_value');
alternatively if you have keys as array you can use this form:
Arr::set($array, ['a', 'b', 'c'], 'new_value');
It isn't the best way to define your keys, but:
$array = [];
$keys = '[a][b][c]';
$value = 'HELLO WORLD';
$keys = explode('][', trim($keys, '[]'));
$reference = &$array;
foreach ($keys as $key) {
if (!array_key_exists($key, $reference)) {
$reference[$key] = [];
}
$reference = &$reference[$key];
}
$reference = $value;
unset($reference);
var_dump($array);
If you have to define a sequence of keys in a string like this, then it's simpler just to use a simple separator that can be exploded rather than needing to trim as well to build an array of individual keys, so something simpler like a.b.c
would be easier to work with than [a][b][c]
Demo