Jump to content

Archived

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

jkies00

Creating an array of directories

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

Share this post


Link to post
Share on other sites
Try this.
[code=php:0]
$myDirectory = opendir("."); //opens directory
while($entryName = readdir($myDirectory)) {
    if (is_dir($entryName) == true) {
        //add it to your array
    }
}[/code]

Hope this helps,
Tom

Share this post


Link to post
Share on other sites
Thanks, Tom - I tried that and it worked.

Also got it to work like this:

[code]while($entryName = readdir($myDirectory)) {
if(filetype($entryName)=="dir"){$dirArray[] = $entryName;}
}[/code]

...but I think your way is cleaner.  Thanks!!

Share this post


Link to post
Share on other sites
Hello,

I noticed something weird - I was able to succesfully create my array, but the first two values in the array are:
.
..

what are they?

Share this post


Link to post
Share on other sites
why would they be in my array?  i only allowed files of type dir.  does php create a dir for each of those that doesn't show in windows explorer view?

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

×

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.