How can the code be optimized to handle the alternating color and image display more efficiently?

To optimize the code for alternating color and image display more efficiently, we can use a loop to iterate through the array of images and colors, and then dynamically generate the HTML code for each item. This way, we can reduce redundancy and improve code readability.

<?php
$items = [
    ['color' => 'red', 'image' => 'red.jpg'],
    ['color' => 'blue', 'image' => 'blue.jpg'],
    ['color' => 'green', 'image' => 'green.jpg'],
];

foreach ($items as $item) {
    echo '<div style="background-color: ' . $item['color'] . ';">';
    echo '<img src="' . $item['image'] . '" alt="' . $item['color'] . '">';
    echo '</div>';
}
?>