2

How do I put every file name on the root directory and and all the file names in each sub folder into an array in php?

1
  • 8
    What about reading the documentation? What about googling for a suggestion? This forum is not for having someone else do your homework. First try yourself to solve the problem, and if you really are stuck, then is the time to write a question here. A good question, containing teh attempt you did until then, code, problem description and all. Commented Sep 9, 2012 at 15:22

5 Answers 5

4

Use scandir() and you'll find a recursive function for sub-directories as well as tons of other examples to achieve what you want.

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

Comments

3

I have always preferred DirectoryIterator and RecursiveDirectoryIterator.

Here is an example:

function drawArray(DirectoryIterator $directory)
{
    $result=array();
    foreach($directory as $object)
    {
        if($object->isDir()&&!$object->isDot())
        {
            $result[$object->getFilename()]=drawArray(new DirectoryIterator($object->getPathname()));
        }
        else if($object->isFile())
        {
            $result[]=$object->getFilename();
        }
    }
    return $result;
}
$array=drawArray(new DirectoryIterator('/path'));
print_r($array);

1 Comment

This is a great suggestion using SPL. Recommended!
1

Have a look at glob() [and give condolence to your RAM by the way if you really want to skim all your files].

Comments

1

This is how I do it.

/**
    Recursively returns all the items in the given directory alphabetically as keys in an array, optionally in descending order.
    If a key has an array value it's a directory and its items are in the array in the same manner.
*/
function scandir_tree($directory_name, $sort_order = SCANDIR_SORT_ASCENDING, $_recursed = false)
    {
    if (!$_recursed || is_dir($directory_name))
        {
        $items = array_diff(scandir($directory_name, (int) $sort_order), ['.', '..']);
        $tree = [];
        foreach ($items as $item)
            {
            $tree[$item] = scandir_tree($directory_name . $item, $sort_order, true);
            }
        return $tree;
        }
    return $directory_name;
    }

Comments

1

Try this:

$ar=array();
$g=scandir('..');
foreach($g as $x)
{
    if(is_dir($x))$ar[$x]=scandir($x);
    else $ar[]=$x;
}
print_r($ar);

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.