How can PHP functions be structured to ensure cleaner code and prevent mixing of header data with table content?
To ensure cleaner code and prevent mixing of header data with table content, PHP functions can be structured to separate the logic for generating headers and table content. By creating separate functions for each task, the code becomes more organized and easier to maintain. This approach also allows for better reusability of code and promotes a modular design.
<?php
// Function to generate table headers
function generateTableHeaders($headers) {
echo '<tr>';
foreach ($headers as $header) {
echo '<th>' . $header . '</th>';
}
echo '</tr>';
}
// Function to generate table rows
function generateTableRows($data) {
foreach ($data as $row) {
echo '<tr>';
foreach ($row as $cell) {
echo '<td>' . $cell . '</td>';
}
echo '</tr>';
}
}
// Example usage
$headers = ['Name', 'Age', 'City'];
$data = [
['John', 25, 'New York'],
['Alice', 30, 'Los Angeles'],
['Bob', 22, 'Chicago']
];
echo '<table>';
generateTableHeaders($headers);
generateTableRows($data);
echo '</table>';
?>
Related questions
-
file_get_contents explode str_replace
-
input validation htmlspecialchars SQL injection
-
PHP cookies subdomains