How can PHP be used to iterate through a folder and categorize images based on their file names?

To iterate through a folder and categorize images based on their file names, you can use PHP's directory functions to loop through the files in the folder, extract the file names, and then classify them based on certain criteria (such as specific keywords or patterns in the file names). You can create an associative array where the keys represent categories and the values are arrays of file names belonging to each category.

<?php
$folder = 'path/to/folder';
$categories = [];

if (is_dir($folder)) {
    if ($handle = opendir($folder)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                // Categorize images based on file names
                if (strpos($file, 'category1') !== false) {
                    $categories['Category 1'][] = $file;
                } elseif (strpos($file, 'category2') !== false) {
                    $categories['Category 2'][] = $file;
                } else {
                    $categories['Other'][] = $file;
                }
            }
        }
        closedir($handle);
    }
}

// Output the categorized images
foreach ($categories as $category => $files) {
    echo $category . ":\n";
    foreach ($files as $file) {
        echo $file . "\n";
    }
}
?>