PHP: Set value of nested array using variable as key PHP: Set value of nested array using variable as key arrays arrays

PHP: Set value of nested array using variable as key


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


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');


Hi bro you can do it like this throught an array of keys :

This is your array structured :

$array = array(    'a'=> array(        'b' => array(            'c'=>'some value',        ),    ),);

This is the PHP code to get value from your array with dynamic keys :

$result = $array; //Init an result array by the content of $array$keys = array('a','b','c'); //Make an array of keys//For loop to get result by keysfor($i=0;$i<count($keys);$i++){    $result = $result[$keys[$i]];}echo $result; // $result = 'new value'

I hope that the answer help you, Find here the PHPFiddle of your working code.