How can separating a script into two parts, one for retrieving images from the filesystem and the other for generating HTML output, improve performance and functionality?

Separating a script into two parts, one for retrieving images from the filesystem and the other for generating HTML output, can improve performance by reducing the amount of processing needed for each request. By separating these tasks, the script can focus on efficiently retrieving images and then generating HTML output separately. This separation also improves functionality by allowing for easier maintenance and scalability as each part can be modified or expanded independently.

// Part 1: Retrieving images from the filesystem
function getImagesFromDirectory($directory) {
    $images = [];
    $files = scandir($directory);
    
    foreach ($files as $file) {
        if (is_file($directory . '/' . $file) && in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'gif'])) {
            $images[] = $file;
        }
    }
    
    return $images;
}

// Part 2: Generating HTML output
function generateImageGallery($images) {
    $html = '<div class="image-gallery">';
    
    foreach ($images as $image) {
        $html .= '<img src="' . $image . '" alt="' . pathinfo($image, PATHINFO_FILENAME) . '">';
    }
    
    $html .= '</div>';
    
    return $html;
}

// Example usage
$images = getImagesFromDirectory('path/to/images');
$imageGallery = generateImageGallery($images);

echo $imageGallery;