Currently Browsing: Home » Reading directories in sequence in PHP

Reading directories in sequence in PHP

In a previous article, kab noted that when he read files using the readdir function in PHP, it would not read in a sequence (eg. 2182.JPG is followed by 2183.JPG, 2184.JPG, 2190.JPG etc.), but rather quite randomly.

The fact is, on certain web servers, such as the one that Lateral Code runs on, readdir reads in sequential order, while many others do not. If you’re on a web server that does not read in sequential order, there is a very simple fix you can do.

directory listing

First, let’s start with the base directory reading loop:


	if ( $handle = opendir($path) ) {
		while ( ($file = readdir($handle)) !== false ) {
			// Do stuff here
		}
	}

This is the code that allows us to read the files from a directory. However, as stated above, on certain web servers, files are read in random order.

I believe that the simplest way to get the files in order is to save the files to an array, and then sort the array. This allows us to pull them back out in order:


	if ( $handle = opendir($path) ) {
		$files = array();
		while ( ($file = readdir($handle)) !== false ) {
			$files[] = $file;
		}
		sort($files);
		foreach ( $files as $file ) {
			// Do stuff here
		}
	}

In this snippet, we first create the array $files. Then, in the while loop, instead of performing an action there, we append $file to the end of the array. The sort function sorts the array into sequential order from lowest to highest. Then, the foreach loop goes through the now sorted array, fetching the files in order. We can now perform actions on the files in sequential order.

The sort function arranges things from lowest to highest. For example, using sort on the array "lemon", "orange", "banana", "apple" would produce "apple", "banana", "lemon", "orange".

However, a problem with the sort function is that it’s “not natural”, as in, if you sort "img12.png", "img10.png", "img2.png", "img1.png", it will come out as "img1.png", "img10.png", "img12.png", "img2.png". In this case, it might make mores sense to use the natsort function or the natcasesort function, which is the case-insensitive version of natsort. Using natsort with the images example would provide "img1.png", "img2.png", "img10.png", "img12.png".

If you have any other ways or suggestions, feel free to leave them in the comments.

Tags: ,

This entry was posted on Friday, March 27th, 2009 at 06:49:39. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

6 Responses to “Reading directories in sequence in PHP”

  1. kab says:

    Hey Patrick, that’s great. I will try it as soon as I can can.

  2. Haradeep says:

    Hi, I tried it. I failed many many times to sort my images. Your concept is correct, but I failed. Can you please add complete code of index.php using these please.

  3. Ida says:

    Yes, I agree with Haradeep. I find this really difficult because I’m not very familiar with PHP and I don’t really know where to insert the code so it works with everything else. When I tried it just failed alltogether. But if you could post the gallery index.php with the sorting included, or just explain where in the code it can be added, it would be really great. And thank for a very neat PHP gallery. :)

  4. It’s quite simple actually. I’m no guru but I placed the code exactly as he described.

    In his previous post, he posted :

    # SETTINGS
    $max_width = 100;
    $max_height = 100;

    function getPictures() {
    global $max_width, $max_height;
    if ( $handle = opendir(“.”) ) {
    $lightbox = rand();
    echo ”;
    while ( ($file = readdir($handle)) !== false ) {
    if ( !is_dir($file) ) {
    $split = explode(‘.’, $file); ///and so on

    What id did was insert this snippet of his code on this post:

    {
    $files[] = $file;
    }
    sort($files);
    foreach ( $files as $file )

    After this point in the original code:

    function getPictures() {
    global $max_width, $max_height;
    if ( $handle = opendir(“.”) ) {
    $lightbox = rand();
    echo ”;
    while ( ($file = readdir($handle)) !== false

    before the:

    {
    if ( !is_dir($file) ) {
    $split = explode(‘.’, $file); ///and so on

    Works like a charm! Thank you Patrick!

  5. Sadique PK says:

    Great.. Thanks…. I was struggling for a day…

  6. Ade_D says:

    Hi,
    FANTASTIC set of tutorials – cheers!
    I can’t get my directory reading in sequence *and* pagination working (form your other post).

    Any ideas??

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.