Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

How to Sort Images in a PHP Gallery from a Directory

PHP’s scandir() sorts names alphabetically by default, not by upload or capture date. Filter image files and apply a sorting rule that matches the gallery’s intended order.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

$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:

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

File modification time

If the desired order is by modification time, sort using that specific field rather than assuming the directory listing represents chronology:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
usort($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.

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_NONE to 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

  1. Check that the directory path is correct and that scandir() did not fail.
  2. Inspect the filtered image array immediately before rendering.
  3. Apply the chosen sorting rule to that array.
  4. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.