Jump to content

Creating an array of directories


jkies00

Recommended Posts

Hello,

I'm trying to create an array of directories within a specific directory:

[code]$myDirectory = opendir("."); //opens directory
while($entryName = readdir($myDirectory)) {
if(strcmp(filetype($entryName),"dir")==0)){$dirArray[] = $entryName;}  // if the filetype is a directory, add it to the array
}[/code]

The script works if I take out the if statement, but lists files and folders alike.  I'd like to get a list of only the folders.  What am I doing wrong here?  Any opinions welcome, I'm a n00b.  :o)

~jk

Link to comment
https://forums.phpfreaks.com/topic/19796-creating-an-array-of-directories/
Share on other sites

Here is a function for creating an array of both files and directories. I think that this sinpett came from Jenk

[code]
<?php

function filelist($dir)
{
    if (!$dir = realpath($dir)) return null;

    static $files = array();
    static $dirs = array();

    $handle = opendir($dir);

    while (($file = readdir($handle)) !== false)
    {
        if (!in_array($file, array('.', '..')))
        {
            if (is_dir($path = ($dir . DIRECTORY_SEPARATOR . $file)))
            {
                $dirs[] = $path;
                filelist($path);
            } else {
                $files[] = $path;
            }
        }
    }
   
    return array('dirs' => $dirs, 'files' => $files);
}

echo nl2br(print_r(filelist('.'), true));

?>[/code]

This will create an array with the directories and files in it. You can modify it to suit your needs.

Good Luck,
Tom

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.