To invest in each other the elements of the array?

There is a one-dimensional array of the form
[0] => dir2
[1] => dir2_1
[2] => dir2_1_1
...

The element may be a single, maybe a lot.
How to get the output of their nested within each other in such a way?
array(
"dir2"=>array(
"dir2_1"=>array(
"dir2_1_1"=>array(...)
)
)
)
June 8th 19 at 16:45
1 answer
June 8th 19 at 16:47
Solution
Possible recursion: https://3v4l.org/m5Cup
<?php

$input = ['dir2', 'dir2_1', 'dir2_1_1'];

function convert_array(array $input, array $output = []) {
 if (empty($input)) {
 return $output;
}

 $value = array_pop($input);

 return convert_array($input, [$value =--> $output]);
}

var_dump(convert_array($input));


It is possible and without a recursion: https://3v4l.org/4FuZ4
<?php

$input = ['dir2', 'dir2_1', 'dir2_1_1'];

$output = [];
foreach (array_reverse($input) as $value) {
 $output = [$value =--> $output];
}

var_dump($output);
+1 to username - una commented on June 8th 19 at 16:50

Find more questions by tags PHPArrays