Search code examples
phparraysmultidimensional-arrayeval

Array: set value using dot notation?


Looking into Kohana documentation, i found this really usefull function that they use to get values from a multidimensional array using a dot notation, for example:

$foo = array('bar' => array('color' => 'green', 'size' => 'M'));
$value = path($foo, 'bar.color', NULL , '.');
// $value now is 'green'

Im wondering if there is a way to set the an array value in the same way:

set_value($foo, 'bar.color', 'black');

The only way i found to do that is re-building the array notation ($array['bar']['color']) and then set the value.. using eval.

Any idea to avoid eval?


Solution

  • function set_val(array &$arr, $path,$val)
    {
       $loc = &$arr;
       foreach(explode('.', $path) as $step)
       {
         $loc = &$loc[$step];
       }
       return $loc = $val;
    }