Skip to content
PHP Logo

What are some ways to categorize and display images based on their file names using PHP?

One way to categorize and display images based on their file names using PHP is to create separate folders for each category and move images to the corresponding folder based on their file names. Then, you can use PHP to scan the folders and display images accordingly.

php
// Define the directory where images are stored
$directory = 'images/';

// Scan the directory for image files
$files = scandir($directory);

// Loop through each file
foreach ($files as $file) {
    // Check if the file is an image
    if (in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'gif'])) {
        // Categorize the image based on its file name
        if (strpos($file, 'category1') !== false) {
            echo '<img src="' . $directory . $file . '" alt="Image 1">';
        } elseif (strpos($file, 'category2') !== false) {
            echo '<img src="' . $directory . $file . '" alt="Image 2">';
        } else {
            echo '<img src="' . $directory . $file . '" alt="Other Image">';
        }
    }
}