This question has already been answered:

There is an array:

$array = ['key1'=>['key2'=>'val']]; 

In the line through the dot are the keys of the array:

 $keys_string = 'key1.key2'; 

You need to change the value of the array using the keys specified through a dot in the $ keys_string variable.

Reported as a duplicate by participants Ipatiev , AK , Vadim Ovchinnikov , rjhdby , aleksandr barakin Jan 22, '17 at 11:44 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    The next question will be "Delete the value of the array with the keys in the string"? How many more questions are there in the ticket? - Ipatiev
  • @ Ipatiev are really different questions, therefore, 2 topics. - Konstantin

1 answer 1

If only 2 levels of nesting

 $keys = explode(".", $keys_string); $array[$keys[0]][$keys[1]] = 'val' 

Or if not level 2

 $keys = explode(".", $keys_string); foreach($item as $keys) { $val = &$array[($item]; } $val = 'test'; 

UPDATED

Essence - get on the link to change the array

 $array = ['key1'=>['key2'=>'val']]; $keys_string = 'key1.key2'; $keys = explode(".", $keys_string); foreach($keys as $key) { $val = &$array[$key]; } $val = 'test'; var_dump($array); 
  • Thank you, unfortunately the level may be different. - Konstantin
  • @Konstantin then $ val = "; foreach ($ item as $ keys) {$ val = $ array [($ item];} $ val = 'test'; - Kostiantyn Okhotnyk
  • the point is to sort through the array until $ keys are finished, and then the last value will be the result - Kostiantyn Okhotnyk
  • let's say we have $ array = ['key1' => ['key2' => 'val']]; $ keys = explode (".", $ keys_string); // [key1, key2] the first iteration of the loop will be $ val = 'key1' => ['key2' => 'val'], and in the second 'key2' => 'val', exit the loop and get the last value - Kostiantyn Okhotnyk
  • add all the reasoning by editing the answer - Naumov