php – Set values ​​from an array recursively

Question:

Assuming I have the following array

array(
'chave1' => 'valor1',
'chave2' => array(
    'chave3' => 'valor2',
    'chave4' => array(
        'chave5' => 'valor3'
    )
))

And in this array I need to set the value of key 5, but without needing to go level by level, I could pass it to a function like this:

setar_valor('chave2.chave4.chave5', 'meu novo valor');

And this function would interpret that each . would be a new level within the array.

I already racked my brain about it, but I can't think of how to do it :/

Answer:

You can make a function that goes "diving" by reference in this array, following the keys (deep levels) extracted from that string with $niveis = explode('.', $path);

Using & you can reference arrays, so when you have $foo = $array[$key]; by changing $foo you are changing the value of $array[$key] .

function setar_valor($path, $str, &$array){
    $niveis = explode('.', $path);
    $temp = &$array;
    foreach ( $niveis as $key ) {
        $temp = &$temp[$key];
    }
    $temp = $str;
}

Example: https://ideone.com/H6D3Og

The full code:

$arr = array(
'chave1' => 'valor1',
'chave2' => array(
    'chave3' => 'valor2',
    'chave4' => array(
        'chave5' => 'valor3'
    )
));

function setar_valor($path, $str, &$array){
    $niveis = explode('.', $path);
    $temp = &$array;
    foreach ( $niveis as $key ) {
        $temp = &$temp[$key];
    }
    $temp = $str;
}

setar_valor('chave2.chave4.chave5', 'meu novo valor', $arr);
var_dump($arr);

Result:

array(2) {
  ["chave1"]=>
  string(6) "valor1"
  ["chave2"]=>
  array(2) {
    ["chave3"]=>
    string(6) "valor2"
    ["chave4"]=>
    array(1) {
      ["chave5"]=>
      string(14) "meu novo valor"
    }
  }
}
Scroll to Top