I'm trying to create an array while parsing a string separated with dots
$string = "foo.bar.baz";
$value = 5
to
$arr['foo']['bar']['baz'] = 5;
I parsed the keys with
$keys = explode(".",$string);
How could 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 out if this, passing the string and the value as parameter and returning the array.
You can try 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)
}
}
}
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With