Hacking with PHP has been updated for PHP 7 - click here! >>

One last directory function

array scandir ( string dirname [, int sorting_order [, resource context]])

Scandir() is a neat function that takes a minimum of one parameter with an optional second. Parameter one is the path of a directory you want to work with - scandir() returns an array of all files and directories in the directory you specify here. Parameter two, if included and set to 1, will sort the array returned reverse alphabetically - if it is not set, the array is returned sorted alphabetically.

This next script prints out a list of all the files and directories in the current directory, with reverse sorting:

    $files = scandir(".", 1);

Using scandir() is a quick alternative to calling readdir() repeatedly, and is particularly helpful when you use the second parameter.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Remote files >>

Previous chapter: Deleting directories

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.