How can PHP loops be effectively used in gallery scripts to ensure efficient data retrieval and display?

When creating gallery scripts in PHP, loops can be used to efficiently retrieve and display images from a database or directory. By using a loop, you can dynamically generate HTML markup for each image, reducing repetitive code and making it easier to manage large sets of images. Additionally, loops can be used to implement pagination, allowing for the display of a limited number of images per page.

// Example PHP loop to retrieve and display images in a gallery

// Connect to database or specify image directory
$images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg"];

// Loop through the array of image filenames and generate HTML markup
foreach ($images as $image) {
    echo '<img src="path/to/images/' . $image . '" alt="' . $image . '">';
}