Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
function get_files( $source_directory, $extensions = 'jpg' ) {
$directory = new DirectoryIterator( $source_directory );
$files = new ExtensionFilter( $directory, (array)$extensions );
return $files;
class ExtensionFilter extends FilterIterator {
protected $extensions;
function __construct( Iterator $iterator, $extensions ) {
parent::__construct( $iterator );
$this->extensions = $extensions;
public function accept() {
return in_array( pathinfo( $this->current()->getFilename(), PATHINFO_EXTENSION ),
$this->extensions );

What are the benefits of this process over the one used in David Walsh's example -


mgrabovsky commented Mar 22, 2011

I think the main advantage is that it's much clearer and the code is more modular and maintainable. If you're doing this just for one gig it doesn't really matter what you use though.

Thanks for the answer.

Substituting this into David Walsh's example seems to work just fine, but it prevents sorting the results using code suggested in this comment:

What would need to be done differently for this?


mgrabovsky commented Mar 26, 2011

I don't know if it has anything to do with the OS or FS, but for me the files are always sorted (Windows, NTFS).


mgrabovsky commented Mar 27, 2011

Now, testing it on Ubuntu, ext4, it indeed doesn't sort automagically. I'll see what I can do.

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