What are some alternative methods in PHP to display different text content based on the existence of a related text file for an image?

When displaying images on a website, it can be useful to show different text content based on the existence of a related text file for each image. One way to achieve this is by checking if a text file exists for each image and then displaying the content of the text file if it exists. This can be done using PHP's file_exists() function to check for the existence of the text file.

<?php
// Path to the directory containing images and text files
$directory = 'images/';

// Get list of images in the directory
$images = glob($directory . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

// Loop through each image
foreach ($images as $image) {
    // Check if a text file exists for the image
    $textFile = str_replace('images/', 'text/', $image) . '.txt';
    if (file_exists($textFile)) {
        // Display the text content from the text file
        echo file_get_contents($textFile);
    } else {
        // Display a default message if no text file exists
        echo 'No description available for this image.';
    }
}
?>