Search code examples
phparraysmultidimensional-arraykeypaths

Convert dot-delimited keypath string and a value declaration to a multidimensional associative array


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?


Solution

  • 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.