Home >Backend Development >PHP Tutorial >How to Dynamically Generate an HTML Table from a PHP Array?
How to Create a Dynamic HTML Table from a PHP Array
Generating HTML tables from PHP arrays is a common requirement. Let's explore how to accomplish this with a specific scenario in mind.
Creating a Table with Headings and Data
Suppose we have an array named $shop with the following structure:
$shop = array( array("rose", 1.25, 15), array("daisy", 0.75, 25), array("orchid", 1.15, 7 ), );
To create a table from this array, we can use the following steps:
1. Prepare the Data
It's preferable to modify the array structure by adding column names as keys:
$shop = array( array("title" => "rose", "price" => 1.25, "number" => 15), array("title" => "daisy", "price" => 0.75, "number" => 25), array("title" => "orchid", "price" => 1.15, "number" => 7) );
2. Generate HTML
We can use PHP loops and the implode() function to generate the table markup:
if (count($shop) > 0): ?> <table> <thead> <tr> <th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th> </tr> </thead> <tbody> <?php foreach ($shop as $row): array_map('htmlentities', $row); ?> <tr> <td><?php echo implode('</td><td>', $row); ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif; ?>
Result
This code will generate a valid HTML table with the data from the $shop array, including the specified headings of "title", "price", and "number".
The above is the detailed content of How to Dynamically Generate an HTML Table from a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!