Click to See Complete Forum and Search --> : simle function to list all files in particular dir


madrazel
04-23-2007, 12:52 PM
i wrote this monster :cool: :


function dirdir($x) {
$cwd= getcwd(); $x = strtr($x,"\\","/");

if (stripos($x,"/")) {
$fil = substr(strrchr($x,"/"),1,strlen($x));
$dir = substr($x,0,strlen($x)-strlen($fil));
} else { $dir = $cwd; $fil = $x;};


chdir($dir);
foreach ( glob($fil) as $file ) {
if (!is_file(getcwd()."/".$file)) continue;
$files[]=$file; }
chdir($cwd);
if (@!is_array($files)) return FALSE;
sort($files); return $files; };

//print_r(dirdir("d:\somedir\somedir\*.php"));



do you have any ideas or tips that i can use here, to make it faster or maybe add some simple feature ?

did i make something wrong here ? :confused:

NogDog
04-23-2007, 02:53 PM
I might do it like this:

<?php
function dirdir($path)
{
if(dirname($path) != basename($path))
{
if(!@chdir(dirname($path)))
{
user_error("dirdir(): invalid path", E_USER_WARNING);
return(FALSE);
}
$path = basename($path);
}
$files = glob($path);
$dirs = glob($path, GLOB_ONLYDIR);
$files = array_diff($files, $dirs);
sort($files);
return (count($files)) ? $files : FALSE;
}

laserlight
04-23-2007, 03:22 PM
I think that you engage in some imaginative but rather unnecessary use of strrchr() and strlen() :)

This is my improved version, keeping to your central ideas:
function dirdir($pattern) {
$cwd = strtr(getcwd(), '\\', '/');
$pattern = strtr($pattern, '\\', '/');

if (($pos = strrpos($pattern, '/')) !== false) {
$dir = substr($pattern, 0, $pos + 1);
$file_pattern = substr($pattern, $pos + 1);
} else {
$dir = $cwd . '/';
$file_pattern = $pattern;
}

$files = array();
chdir($dir);
foreach (glob($file_pattern) as $file) {
if (is_file($dir . $file))
$files[] = $file;
}

chdir($cwd);
sort($files);
return $files;
}
This thread probably belongs to the code critique forum, actually.

It may be reasonable to consider the use of natsort() or natcasesort() instead of just sort().