If images in a PHP gallery appear in the wrong order, check the array of image paths immediately before the gallery loop. PHP’s scandir() sorts entries alphabetically by default—not by upload time, capture date, or a custom gallery sequence. Filter out non-images, then sort the remaining files according to the order you actually want.
Check the file list before changing the gallery
Inspect the final array immediately before the code renders the images. For example, temporarily add var_dump($images); before the gallery loop, then compare the listed paths with the intended sequence. If the array is already in the right order, the problem is likely later in the rendering or client-side code rather than in directory sorting.
As an Amazon Associate I earn from qualifying purchases.
Also confirm the configured path points to the intended directory. The PHP scandir() manual says the function returns an array of filenames on success, or false on failure; a path that is not a directory also produces an E_WARNING.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Filter directory entries to supported image files
scandir() returns directory entries, not a ready-made list of gallery images. Its results can include the special entries . and .., subdirectories, and files your gallery does not support. Filter those out before rendering.
#1 Best Overall
$directory = __DIR__ . '/images';
$entries = scandir($directory);
if ($entries === false) {
throw new RuntimeException('Could not read the image directory.');
}
$images = array_values(array_filter($entries, function ($name) use ($directory) {
if ($name === '.' || $name === '..') {
return false;
}
$path = $directory . DIRECTORY_SEPARATOR . $name;
if (!is_file($path)) {
return false;
}
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
return in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true);
}));
This example checks extensions and excludes directories. Adjust the extension list to match the image formats the gallery is designed to display.
Choose an ordering rule that matches the gallery
The manual states, “By default, the sorted order is alphabetical in ascending order.” That behavior is predictable, but it does not tell PHP what sequence the gallery owner intends. Choose an explicit rule:
Rank #2
| Ordering rule | When it fits | Important limitation |
|---|---|---|
| Alphabetical filename | Names themselves define a useful sequence. | Numbers in names are compared as text; for instance, photo10.jpg can come before photo2.jpg. |
| Natural or numeric filename | Filenames contain sequence numbers such as photo1.jpg, photo2.jpg, and photo10.jpg. |
Use a consistent naming scheme so the intended sequence is unambiguous. |
| Timestamp | The gallery should follow a chronology. | Decide whether chronology means file modification time, upload time, or EXIF capture time; those values are not interchangeable. |
| Saved explicit sequence | The owner chooses a custom editorial order. | Store and maintain an order value for each image. |
| Unsorted enumeration | Order does not matter. | SCANDIR_SORT_NONE requests unsorted output; it does not create a meaningful or dependable gallery order. |
Apply the sort explicitly
Alphabetical filenames
To use ascending alphabetical order, sort the filtered names explicitly. This makes the intended behavior clear even though scandir() already sorts alphabetically by default.
sort($images, SORT_STRING);
For descending alphabetical order, use rsort($images, SORT_STRING);.
Names with sequence numbers
If filenames contain numbers and you want numeric-aware ordering, use a natural comparison:
natsort($images);
$images = array_values($images);
Alternatively, use zero-padded names such as photo01.jpg, photo02.jpg, and photo10.jpg with ordinary alphabetical sorting. Padding is a simple option when you control how files are named.
Rank #4
File modification time
If the desired order is by modification time, sort using that specific field rather than assuming the directory listing represents chronology:
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11usort($images, function ($a, $b) use ($directory) {
return filemtime($directory . DIRECTORY_SEPARATOR . $a)
<=> filemtime($directory . DIRECTORY_SEPARATOR . $b);
});
This example puts older modification times first. Reverse the comparison for newest first. Modification time can change when a file is edited or copied, so it may not represent when the image was uploaded or captured.
Upload, capture, or editorial order
For upload chronology, save an upload timestamp when each image is added; filesystem modification time is not a reliable substitute. For capture chronology, read and validate the relevant EXIF date when the image is ingested, since not every image necessarily has usable metadata. For a hand-curated sequence, store an explicit position value in a database or other gallery metadata and sort by that value.
Quick Recap
Common fixes that do not establish the intended order
- Relying on directory enumeration: filesystem enumeration is not an upload or editorial sequence. Sort by a defined key instead.
- Using
SCANDIR_SORT_NONEto fix ordering: it disables sorting; it does not specify which image should come first. - Sorting names lexically when they contain numbers: use natural sorting or zero-pad the numeric part.
- Assuming modification time means upload time: choose and store the timestamp that corresponds to the chronology the gallery needs.
Verify the result
- Check that the directory path is correct and that
scandir()did not fail. - Inspect the filtered image array immediately before rendering.
- Apply the chosen sorting rule to that array.
- Inspect the array again. If its order is correct but the page is not, investigate the rendering loop or client-side code.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




