In what ways can the PHP code for displaying images in a table be made more modular and portable for future changes?
To make the PHP code for displaying images in a table more modular and portable for future changes, we can encapsulate the logic for generating the table rows into a separate function. This function can take parameters such as the image URLs and alt text, allowing for easy customization and reuse in different parts of the code.
<?php
function generateImageTableRow($imageUrl, $altText) {
echo "<tr>";
echo "<td><img src='$imageUrl' alt='$altText'></td>";
echo "</tr>";
}
// Example usage
$imageUrls = ["image1.jpg", "image2.jpg", "image3.jpg"];
$altTexts = ["Image 1", "Image 2", "Image 3"];
echo "<table>";
foreach ($imageUrls as $key => $imageUrl) {
generateImageTableRow($imageUrl, $altTexts[$key]);
}
echo "</table>";
?>