Here's an approach with foreach and no recursion that works:
function buildArray($array) { $new = array(); $current = &$new; foreach($array as $key => $value) { $current[$value] = array(); $current = &$current[$value]; } return $new; }
[ Demo ]
Now your function ... first, using $build[$array[0]] , without defining it as an array, first creates E_NOTICE . Secondly, your function goes into infinite recursion because you are not actually changing $array ( $temp not the same), so count($array) > 0 will be true for all eternity.
And even if you modified $array , you could no longer use $array[0] , because you canceled this, and the indexes will not just move up. For this you need array_shift .
After that, you pass $build and $temp to your function, which leads to the future, because now you assign $build to $temp , so you create another loop in an already endlessly repeating loop.
I tried to fix all of the above in your code, but in the end I realized that my code was now exactly the same as Pevara's answer , but with different variable names, so ... what is it.
source share