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.
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.