Home > Backend Development > PHP Tutorial > How to Generate HTML Tables from PHP Arrays?

How to Generate HTML Tables from PHP Arrays?

Barbara Streisand
Release: 2024-11-25 12:58:10
Original
922 people have browsed it

How to Generate HTML Tables from PHP Arrays?

Creating HTML Tables from PHP Arrays

PHP allows us to construct HTML tables from arrays, providing a convenient way to display tabular data. To generate a table with header labels 'title', 'price', and 'number', we proceed as follows:

Data Initialization

The given PHP array in the question, $shop, represents the data for our table. However, for better organization, it's preferable to explicitly label each field with keys like "title", "price", and "number." This ensures clarity and simplifies table generation.

$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)
);
Copy after login

Constructing the Table

With the data initialized correctly, we can proceed to build the HTML table:

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; ?>
Copy after login

Breaking Down the Code

  • The and tags define the header and body of the table.
  • The code within array_keys(current($shop)) grabs the header labels from the first row of the array.
  • The htmlentities() function ensures that any HTML characters within the data are properly escaped.
  • The foreach loop iterates through each row in the array, generating a new table row for each one.

The above is the detailed content of How to Generate HTML Tables from PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template