09
Aug '12

DirectoryIterator vs scandir in PHP

Having struggles with the limitations of PHP’s scandir in the past, I was delighted to discover DirectoryIterator. It traverses through a directory just as scandir does but for each file or subfolder it finds, you get an object that provides easy access to all the properties of the file. It is also very very simple to implement:

foreach (DirectoryIterator($directory) as $file_or_folder) {
	if ($file_or_folder->isFile()) {
		//do something
	}
	elseif($file_or_folder->getExtension() == 'jpg') {
		//do something else
	}
	//etc
}

Leave a Reply