0

I have an array structure that represents the file system structure

Array
(
    [.config] => Array
        (
            [0] => database.ini
            [1] => javascript.ini
            [3] => project.ini
            [5] => session.ini
            [6] => system.ini
            [.plugins] => Array
                (
                    [0] => comments.ini
                    [1] => user.ini
                )
...

I want to represent each file with its full (relative) path

Array
(
    [0] => config/database.ini
    [1] => config/javascript.ini
    [3] => config/project.ini
    [5] => config/session.ini
    [6] => config/system.ini
    [7] => config/plugins/comments.ini
    [8] => config/plugins/user.ini
...

For the purpose I wrote this function

function recur($elem){
    if(is_array($elem)){
        return recur($elem);
    }else{
        return $elem;
    }
}

And it is giving me

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes)

2 Answers 2

3

The problem is that your recursive function is never terminating, you pass in an array, then if this is an array you recall the same function with the same array, and so on.

What you should do is recurse the nested levels:

function recur($elem){
  foreach($elem as $nested){
    if(is_array($nested)){
      return recur($nested);
    }else{
      return $nested;
    }
  }
}

In this way you use the function on the nested array, instead of the outer you are already processing, note you may have to slightly change the if/else condition depending on the wanted output, in fact returning means exiting the foreach, if you want to walk all the array level you should avoid return and use an accumulator to accumulate the results, but as I said, it depends on the desired output.

Sign up to request clarification or add additional context in comments.

Comments

0

PHP is trying to use more memory than allowed (in your case it is limited to 128 MiB).

You have to adjust the memory_limit in php.ini (see http://www.ducea.com/2008/02/14/increase-php-memory-limit/) or find a way that you do not need to store all paths in memory.

But this won't fix your issue as your recur-method enters an infinite recursion (it calls itself with the exact same parameter as it was called, and, thus, it is never terminating - increasing the php memory limit won't fix this, as you then might run into a stack overflow).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.