Format simple array in multidimensional I have a simple array in PHP like this :
Array
(
    [max_size_video] =&gt; 50000
    [max_size_photo] =&gt; 8000
    [token_expire] =&gt; 100
    [dns] =&gt; mydns.fr
    ...
)

I would like to convert this array to multidimensional format with underscore as a separator:
Array
(
    [max] =&gt; Array
        (
            [size] =&gt; Array
                (
                    [video] =&gt; 50000
                    [photo] =&gt; 8000
                )
        )
    [token] =&gt; Array
        (
            [expire] =&gt; 100
        )
    [dns] =&gt; mydns.fr
    ...
)

I can do this with the following ugly code :
$item = explode('_', $row);
switch (count($item)) {
  case 1:
    $array[$item[0]] = $value;
  break;
  case 2:
    $array[$item[0]][$item[1]] = $value;
  break;
  case 3:
    $array[$item[0]][$item[1]][$item[2]] = $value;
  break;
  case 3:
    $array[$item[0]][$item[1]][$item[2]][$item[3]] = $value;
  break;
  ...
}

How can I do this with a more elegant function?
A reference variable will save you from that wicked code bloat!
You can make iterative calls of this Stack Overflow answer from 2012.
Code: (Demo)
function assignArrayByPath(&amp;$arr, $path, $value, $separator = '_') {
    $keys = explode($separator, $path);
    foreach ($keys as $key) {
        $arr = &amp;$arr[$key];
    }
    $arr = $value;
}
    
foreach ($array as $key =&gt; $value) {
    unset($array[$key]);
    assignArrayByPath($array, $key, $value);
}
var_export($array);


Or boil it down to this: (Demo)
function assignArrayByPath(&amp;$result, $path, $value) {
    foreach (explode('_', $path) as $key) {
        $result = &amp;$result[$key];
    }
    $result = $value;
}

$result = [];
foreach ($array as $key =&gt; $value) {
    assignArrayByPath($result, $key, $value);
}
var_export($result);

This technique will require that you build logical (non-monkey-wrenching) paths as keys.  I mean:

If after 'max_size_photo' =&gt; 8000, you declare 'max' =&gt; 10000, then you will get an error.
If after 'max_size_photo' =&gt; 8000, you declare 'max_size' =&gt; 10000, then you will erase the previously expanded (deeper) elements from the output array.


p.s. You can also write it without any custom functions by nesting the loops so long as you maintain the technique of using a reference variable inside of a reference variable.  Trippy, right?
Code: (Demo)
$result = [];
foreach ($array as $path =&gt; $value) {
    $ref = &amp;$result;
    foreach (explode('_', $path) as $key) {
        $ref = &amp;$ref[$key];
    }
    $ref = $value;
}
var_export($result);