Home > Backend Development > PHP Tutorial > How to convert array to HTML table in PHP

How to convert array to HTML table in PHP

王林
Release: 2023-07-07 21:32:02
Original
1597 people have browsed it

How to convert an array into an HTML table in PHP

In web development, we often encounter the need to present data in tabular form. As a powerful server-side scripting language, PHP provides many convenient functions for operating arrays and generating HTML. We can use these functions to convert arrays into HTML tables.

Below, we will introduce a simple method to implement this function. First, we need to have an array containing data. The following is a sample array:

$data = [
    ['Name', 'Age', 'Gender'],
    ['John', 25, 'Male'],
    ['Jane', 28, 'Female'],
    ['Tom', 22, 'Male']
];
Copy after login

Next, we will use a foreach loop to traverse the array and generate the corresponding HTML code. Here we use a variable $table to save the generated HTML code.

$table = "<table>";
foreach($data as $row) {
    $table .= "<tr>";
    foreach($row as $cell) {
        $table .= "<td>" . $cell . "</td>";
    }
    $table .= "</tr>";
}
$table .= "</table>";
Copy after login

In the above code, we treat each row element in the array as a row of the table, and each cell element as each cell of the row.

Finally, we can use this $table variable in the HTML page to display the generated table.

<html>
<head>
    <title>Array to HTML Table</title>
</head>
<body>
    <?php echo $table; ?>
</body>
</html>
Copy after login

The above code will output the following HTML code:

<table>
    <tr>
        <td>Name</td>
        <td>Age</td>
        <td>Gender</td>
    </tr>
    <tr>
        <td>John</td>
        <td>25</td>
        <td>Male</td>
    </tr>
    <tr>
        <td>Jane</td>
        <td>28</td>
        <td>Female</td>
    </tr>
    <tr>
        <td>Tom</td>
        <td>22</td>
        <td>Male</td>
    </tr>
</table>
Copy after login

With the above code, we can convert the array $data into an HTML table containing table data.

In addition to the above methods, PHP also provides some other functions to quickly generate HTML tables, such as converting arrays into JSON data, and then dynamically generating tables through JavaScript. According to the specific needs, we can choose the appropriate method to achieve it.

The above is the detailed content of How to convert array to HTML table in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template