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?
None of the examples here worked for me, so I came up with a solution using eval() (read about the risks here, but if you don't use user data, it shouldn't be much of an issue). The if-clause in the set-method allows you to push your item onto a new or existing array at that location ($location[] = $item).
Example usage:
Output:
Look at https://gist.github.com/elfet/4713488
I created a small class just for this!
http://github.com/projectmeta/Stingray
Updated @hair resins' answer to cater for:
When a sub-path is not an array
That way you can set the following values more than once to the same variable.
You can make these two ways (by static variable and reference variable):