I am trying to create an array while parsing a string separated by dots
$string = "foo.bar.baz"; $value = 5
to
$arr['foo']['bar']['baz'] = 5;
I analyzed the keys using
$keys = explode(".",$string);
How can i do this?
You can do:
$keys = explode(".",$string); $last = array_pop($keys); $array = array(); $current = &$array; foreach($keys as $key) { $current[$key] = array(); $current = &$current[$key]; } $current[$last] = $value;
Demo
You can easily make a function if this is by passing a string and value as a parameter and returning an array.
You can try the following solution:
function arrayByString($path, $value) { $keys = array_reverse(explode(".",$path)); foreach ( $keys as $key ) { $value = array($key => $value); } return $value; } $result = arrayByString("foo.bar.baz", 5); /* array(1) { ["foo"]=> array(1) { ["bar"]=> array(1) { ["baz"]=> int(5) } } } */
This has something to do with the question you can find the answer to here:
PHP One level deeper in the array, each loop created
You just need to change the code a bit:
$a = explode('.', "foo.bar.baz"); $b = array(); $c =& $b; foreach ($a as $k) { $c[$k] = array(); $c =& $c[$k]; } $c = 5; print_r($b);