How can JavaScript be used to calculate and adjust table widths in PHP?
When displaying tables in PHP, sometimes the content within the cells may cause the table columns to be wider than necessary. To dynamically adjust the table widths based on the content, JavaScript can be used to calculate the width of each column and adjust them accordingly.
<?php
// PHP code to generate a table with dynamic column widths
// Sample data for the table
$data = [
['Name', 'Age', 'Country'],
['John Doe', 30, 'USA'],
['Jane Smith', 25, 'Canada'],
['Michael Johnson', 35, 'UK']
];
// Output the table with JavaScript to adjust column widths
echo '<table id="myTable">';
foreach ($data as $row) {
echo '<tr>';
foreach ($row as $cell) {
echo '<td>' . $cell . '</td>';
}
echo '</tr>';
}
echo '</table>';
// JavaScript code to calculate and adjust table column widths
echo '<script>
let table = document.getElementById("myTable");
let colCount = table.rows[0].cells.length;
let colWidth = 100 / colCount + "%";
for (let i = 0; i < colCount; i++) {
table.rows[0].cells[i].style.width = colWidth;
}
</script>';
?>