Home >Backend Development >PHP Tutorial >How to Generate an HTML Table from a PHP Array?

How to Generate an HTML Table from a PHP Array?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 22:22:12285browse

How to Generate an HTML Table from a PHP Array?

Generating a HTML Table from a PHP Array

Creating a HTML table from a PHP array is a common task encountered in web development. This can be accomplished by accessing the data present in each element of the array and formatting it accordingly.

Creating a Sample PHP Array

To begin, let's consider the provided PHP array named $shop which holds the product information as [row][column]:

$shop = array(
    array("rose",   1.25, 15), // row 0, columns: title, price, number
    array("daisy",  0.75, 25), // row 1, columns: title, price, number
    array("orchid", 1.15, 7 )  // row 2, columns: title, price, number
);

Formatting HTML Table Data

The next step is to format the PHP array into HTML. As the task specifies, the HTML table should have headings for 'title', 'price', and 'number'. Let's create a PHP script to generate the HTML table:

<?php

// Ensure the array is populated
if (count($shop) > 0) {

    // Write HTML table start
    echo '<table border="1">';
    
    // Write table header row
    echo '<thead><tr>';

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

Statement:
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