# Reading Directories, the easy way!

**URL:** <https://www.phphelp.com/t/reading-directories-the-easy-way/23579>\
**Category:** The Occasional Tutorial\
**Created:** [October 27, 2014, 3:41pm UTC](https://www.phphelp.com/t/reading-directories-the-easy-way/23579 "2014-10-27T15:41:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Redscouse](https://www.phphelp.com/user_avatar/www.phphelp.com/redscouse/32/124_2.png) [@Redscouse](https://www.phphelp.com/u/Redscouse)\
**Post date:** [October 27, 2014, 3:41pm UTC](https://www.phphelp.com/t/reading-directories-the-easy-way/23579/1 "2014-10-27T15:41:53Z")

</div>

Well, I just answered a question in the forums and it struck me that this is a common problem so thought i’d post the solution here for anyone looking for this type of thing. 🙂

This allows us to read any directory including all sub-directories of the starting point.

Ready? Let’s go…

Firstly we are going to create a function - functions are great!  
They keep our code in one place and doesn’t interfere with other code on our page. 🙂  
[php]  
// this function takes two args: a string and an array.  
// $path = string. The path to a folder.  
// $imgtype = array. An array of file types to look for.  
function list\_files($path, $type) {  
$directory = new \RecursiveDirectoryIterator($path);  
$iterator = new \RecursiveIteratorIterator($directory);  
$files = array();  
foreach ($iterator as $info) {  
if (in\_array($info-\>getExtension(), $type)) {  
$files[] = $info-\>getPathname();  
}  
}  
return $files;  
}  
[/php]

Now, to use our newly created function, we do this:  
[php]  
$path = ‘imgs’; // start in this folder/directory  
$type = array(‘png’, ‘jpg’); // find me this type of file…  
$image\_array = list\_files($path, $type); // do it  
[/php]

We now have a nice array of all the files found.  
In this example we searched for files with an extension of ‘png’ or ‘jpg’

- we could indeed search for anything we want, IE: ‘php’ etc.

Let’s take a look at what we found…  
[php]  
// display the results  
print ‘

```
’;
print_r($image_array);
print ‘
```
’;  
/\*  
output:  
Array  
(  
[0] =\> imgs\cat.png  
[1] =\> imgs\dog.png  
[2] =\> imgs\mouse.jpg  
[3] =\> imgs\more\_images\cat2.png  
[4] =\> imgs\more\_images\dog2.png  
[5] =\> imgs\more\_images\mouse2.jpg  
)  
[/php]

Yep, that’s all folks!!  
Searching directories has never been easier thanks to your friendly Redscouse! 🙂

Enjoy,  
Red 😉

---

<div class="post-metadata">

**Author:** ![Topcoder](https://www.phphelp.com/user_avatar/www.phphelp.com/topcoder/32/4356_2.png) [@Topcoder](https://www.phphelp.com/u/Topcoder)\
**Post date:** [October 27, 2014, 11:20pm UTC](https://www.phphelp.com/t/reading-directories-the-easy-way/23579/2 "2014-10-27T23:20:13Z")

</div>

Very Useful!
