How to create a HTML Table from a PHP array?

How to create a HTML Table from a PHP array?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Rendering PHP Arrays as HTML Tables

Converting a multidimensional array into an HTML table is a frequent requirement when building data-heavy views in PHP applications. You often have raw data stored in variables and need to transform that structure into semantic markup for the browser. Consider a scenario where you are displaying flower inventory:

$shop = array(
    array("rose",   1.25, 15),
    array("daisy",  0.75, 25),
    array("orchid", 1.15, 7 ),
);

Your goal is to render this as a table with headers for title, price, and number. While modern frameworks handle this abstraction automatically, understanding the underlying mechanics helps when building custom components or working within legacy codebases.

The Basic Loop Approach

The most straightforward method involves iterating over the rows of your array and generating <tr> elements. You can use a nested loop to construct the table structure. The outer loop iterates through each row (sub-array), while the inner loop extracts individual cells.

echo "<table border='1'>";
echo "<thead><tr>";
echo "<th>title</th><th>price</th><th>number</th></tr></thead>";
echo "<tbody>";

foreach ($shop as $row) {
    echo "<tr>";
    foreach ($row as $cell) {
        echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>";
}

echo "</tbody></table>";

This approach works reliably across different PHP versions. However, it relies on array indices matching the header order exactly. If your data changes or if you need to add a new column later without updating every loop iteration, this method becomes brittle.

Using array_walk for Cleaner Logic

For larger datasets or more complex rendering logic, array_walk can provide a cleaner separation between data and presentation. You can pass an array of headers and a callback function that processes each row. This keeps the main view code concise:

$headers = ['title', 'price', 'number'];

echo "<table>";
echo "<thead><tr>";
foreach ($headers as $h) {
    echo "<th>$h</th>";
}
echo "</tr></thead>";

echo "<tbody>";
array_walk($shop, function($row, $index) use ($headers) {
    echo "<tr>";
    foreach ($headers as $colIndex => $colName) {
        $value = isset($row[$colIndex]) ? $row[$colIndex] : '';
        echo "<td>$value</td>";
    }
    echo "</tr>";
});
echo "</tbody></table>";

This pattern decouples the column names from the raw data structure. It ensures that even if the $shop array contains fewer or more columns than expected, you can control exactly how missing values are handled within the callback.

Security and Data Sanitization

A critical pitfall in dynamic table generation is injecting unsanitized data directly into HTML attributes or content. In the examples above, htmlspecialchars() is essential to prevent Cross-Site Scripting (XSS) attacks. If a flower name contains <script> tags, they must be escaped before rendering.

Additionally, consider how you handle numeric types. The price column might come as a float, while number could be an integer or string. Ensure consistent formatting if your output needs to match specific locale requirements (e.g., using number_format() for currency).

Framework Integration: Laravel

If you are working within the Laravel ecosystem, you likely prefer not to echo raw HTML strings directly from PHP logic. Instead, you should leverage Blade templates. Passing the $shop array to a view allows you to separate concerns effectively.

// In your controller
return view('shop.index', ['shop' => $shop]);

In your Blade file (resources/views/shop/index.blade.php), you can use the @foreach directive:

<table>
    <thead>
        <tr>
            <th>title</th>
            <th>price</th>
            <th>number</th>
        </tr>
    </thead>
    <tbody>
        @foreach($shop as $item)
            <tr>
                <td>{{ $item[0] }}</td>
                <td>{{ $item[1] }}</td>
                <td>{{ $item[2] }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

Laravel's Blade engine automatically escapes output variables by default, reducing the risk of XSS without needing explicit htmlspecialchars calls in every instance. For more advanced layouts, you might explore packages that simplify complex data grids, such as those available on LaravelCompany, which can help abstract table rendering logic further.

Performance Considerations

For small to medium-sized lists, the performance difference between a foreach loop and other methods is negligible. However, if you are generating tables with thousands of rows, avoid heavy string concatenation inside loops. Building the table HTML in a single string buffer or using an array to collect rows before joining them can reduce memory overhead and improve rendering speed in high-traffic environments.

Our network