How can PHP developers efficiently output an array as a table?
To efficiently output an array as a table in PHP, developers can loop through the array and generate the table rows dynamically. This can be achieved by using a foreach loop to iterate over the array elements and outputting the data within table row tags. By dynamically generating the table rows, developers can handle arrays of various sizes without needing to hardcode each row.
<?php
// Sample array to be output as a table
$array = array(
array('Name' => 'John', 'Age' => 25, 'Country' => 'USA'),
array('Name' => 'Alice', 'Age' => 30, 'Country' => 'Canada'),
array('Name' => 'Bob', 'Age' => 22, 'Country' => 'UK')
);
// Output the array as a table
echo '<table border="1">';
echo '<tr><th>Name</th><th>Age</th><th>Country</th></tr>';
foreach($array as $row){
echo '<tr>';
foreach($row as $value){
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</table>';
?>