- PHP

How to make a table from PHP array?

The easiest way to create a table with data from a PHP array is to loop through it, with, for example, a foreach() loop.

Example:

Use a foreach() loop to put the array’s data inside an HTML table.

<?php

// sample data:

$items = [
    'Phone' => '299.99',
    'Laptop' => '699.99',
    'Hammer' => '4.99',
];

?>

<table>
    <thead>
        <th>Item name</th>
        <th>Item price</th>
    </thead>

    <tbody>
        <?php foreach($items as $item => $price) { ?>
            <tr>
                <td><?php echo $item; ?></td>
                <td><?php echo $price; ?></td>
            </tr>
        <?php } ?>
    </tbody>
</table>

Output:

Item name Item price
Phone 299.99
Laptop 699.99
Hammer 4.99