What are some best practices for organizing and structuring PHP code when working with tables and loops?
When working with tables and loops in PHP, it is best practice to separate your logic into functions to improve code readability and maintainability. Additionally, using meaningful variable names and comments can help others understand your code more easily. Lastly, consider breaking down complex loops into smaller, more manageable parts to avoid confusion and potential errors.
<?php
// Function to generate a table with data from an array
function generateTable($data) {
echo '<table>';
foreach($data as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>' . $cell . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
// Sample data array
$data = [
['John', 'Doe', 'john.doe@example.com'],
['Jane', 'Smith', 'jane.smith@example.com'],
['Bob', 'Johnson', 'bob.johnson@example.com']
];
// Call the function to generate the table
generateTable($data);
?>