Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
Strae Avatar asked Oct 21 '11 15:10

Strae


People also ask

What is dot notation?

Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.

What is the use of dot in JavaScript?

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

What is PHP dot notation?

Dot provides an easy access to arrays of data with dot notation in a lightweight and fast way. Inspired by Laravel Collection. Dot implements PHP's ArrayAccess interface and Dot object can also be used the same way as normal arrays with additional dot notation.

How do you echo the value of an array?

To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


1 Answers

Sure it's possible.

The code

function set_value(&$root, $compositeKey, $value) {
    $keys = explode('.', $compositeKey);
    while(count($keys) > 1) {
        $key = array_shift($keys);
        if(!isset($root[$key])) {
            $root[$key] = array();
        }
        $root = &$root[$key];
    }

    $key = reset($keys);
    $root[$key] = $value;
}

How to use it

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

Outputs

Array
(
    [bar] => Array
        (
            [color] => black
        )

)

See it in action.

like image 138
Jon Avatar answered Oct 04 '22 23:10

Jon