What are the advantages of using a function like tabelle() in PHP to generate HTML table output for database data, and how does it contribute to code efficiency and readability?
When displaying database data in an HTML table in PHP, it can be repetitive and error-prone to manually write out the table structure and populate it with data. By using a function like tabelle() to generate the HTML table output, you can encapsulate the logic for creating the table within a reusable function. This not only makes your code more efficient and readable but also allows for easier maintenance and updates in the future.
<?php
// Function to generate HTML table from database data
function tabelle($data) {
$html = '<table>';
foreach ($data as $row) {
$html .= '<tr>';
foreach ($row as $cell) {
$html .= '<td>' . $cell . '</td>';
}
$html .= '</tr>';
}
$html .= '</table>';
return $html;
}
// Example usage
$data = [
['John', 'Doe', '30'],
['Jane', 'Smith', '25'],
['Bob', 'Johnson', '40']
];
echo tabelle($data);
?>
Related questions
-
PHP image download URL
-
OOP procedural programming mysqli functions
-
static scope object scope PHP classes