Skip to content

Instantly share code, notes, and snippets.

@bxt
Created February 26, 2011 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxt/845269 to your computer and use it in GitHub Desktop.
Save bxt/845269 to your computer and use it in GitHub Desktop.
List all files into an array, no dirs, optianally filtered by extension (using scandir)
<?php
function bxt_fileList($d,$x=false){
foreach(scandir($d) as $f)if(is_file($d.'/'.$f)&&(!$x||preg_match('/'.$x.'$/i',$f)))$l[]=$f;
return $l;
}
// silly "ninja" comment code from
// http://de3.php.net/manual/en/function.scandir.php#90628
function file_list($d,$x){
foreach(array_diff(scandir($d),array('.','..')) as $f)if(is_file($d.'/'.$f)&&(($x)?ereg($x.'$',$f):1))$l[]=$f;
return $l;
}
/*
* Funny, this self-declared "NNNIIIinnnjaaa" made me spot 6 issues
* in his four lines of code at first sight.
*
* Problems here:
* - array_diff() doesn't provide anything because . and .. are dirs
* - ereg() is silly, use eregi() istead, sinde file extensions are not case-sensitive
* - ereg()-Functions are depraced since PHP5.3
* - preg_match() is faster anyway
* - ternary is just poor, replace with usual boolean expressions
* - make 2nd parameter explicitly optional
*/
// Testing:
echo "\nhis:\n";
echo implode("\n",file_list('.'));
echo "\n\n\n\nhis.php:\n";
echo implode("\n",file_list('.','php'));
echo "\nmine:\n";
echo implode("\n",bxt_fileList('.'));
echo "\n\n\n\nmine.php:\n";
echo implode("\n",bxt_fileList('.','php'));
@bxt
Copy link
Author

bxt commented Mar 7, 2011

And of course there's the OOP/SPL/PEAR-way of doing things: https://github.com/sebastianbergmann/php-file-iterator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment