How can you optimize the code provided to create a new page after a certain number of images, rather than displaying all images on one page?
To optimize the code to create a new page after a certain number of images, you can modify the loop that displays the images to keep track of the number of images displayed. Once the desired number of images per page is reached, you can close the current page and start a new one. This can be achieved by using a counter variable to keep track of the number of images displayed and conditionally closing and opening new pages based on this counter.
<?php
$images = array("image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg", "image6.jpg");
$imagesPerPage = 3;
$pageCounter = 0;
foreach ($images as $image) {
if ($pageCounter % $imagesPerPage == 0) {
if ($pageCounter > 0) {
echo "</div>"; // Close previous page
}
echo "<div class='page'>"; // Start new page
}
echo "<img src='$image' alt='Image'>";
$pageCounter++;
}
if ($pageCounter > 0) {
echo "</div>"; // Close last page if there are images
}
?>