Convert dot syntax like “this.that.other” to multi-dimensional array in PHP

Try this number…

function assignArrayByPath(&$arr, $path, $value, $separator=".") {
    $keys = explode($separator, $path);

    foreach ($keys as $key) {
        $arr = &$arr[$key];
    }

    $arr = $value;
}

CodePad

It will loop through the keys (delimited with . by default) to get to the final property, and then do assignment on the value.

If some of the keys aren’t present, they’re created.

Leave a Comment