How can one optimize PHP code to display images in a grid format?

To optimize PHP code to display images in a grid format, you can use a loop to iterate through an array of image file paths and output HTML markup for each image in a grid layout. By dynamically generating the grid layout using PHP, you can easily adjust the number of columns or rows in the grid without having to hardcode each image's position.

<?php
// Array of image file paths
$images = [
    'image1.jpg',
    'image2.jpg',
    'image3.jpg',
    'image4.jpg',
    'image5.jpg'
];

// Define number of columns in the grid
$columns = 3;

echo '<div class="grid-container">';
foreach ($images as $image) {
    echo '<div class="grid-item"><img src="' . $image . '" alt="Image"></div>';
}
echo '</div>';
?>