How can PHP be used to read a text file with the same name as an image file in a directory?

To read a text file with the same name as an image file in a directory using PHP, you can first get the list of image files in the directory, extract the filename without the extension, and then read the corresponding text file with the same name. This can be achieved by using functions like scandir() to get the list of files, pathinfo() to extract the filename, and file_get_contents() to read the text file.

$directory = 'path/to/image/directory/';
$files = scandir($directory);

foreach($files as $file) {
    if(pathinfo($file, PATHINFO_EXTENSION) == 'jpg') {
        $filename = pathinfo($file, PATHINFO_FILENAME);
        $textFile = $directory . $filename . '.txt';
        
        if(file_exists($textFile)) {
            $textContent = file_get_contents($textFile);
            echo "Text content for $file: $textContent <br>";
        }
    }
}