PHP: Table Class

After some playing with PHP, I wanted to create a new class but I didn’t really know what. So after some time I founded a nice task to do :). So here is my “Table Class”. It’s a easy way to create a HTML table from a PHP array.

The code:

 1<?php
 2 
 3class Table
 4{
 5    private string $output;
 6
 7    function __construct()
 8    {
 9        $this->output = "<table>\r";
10    }
11   
12    function addSingleRow($arr)
13    {
14        if (is_array($arr)) {
15            $output = "\t<tr>\r";
16           
17            foreach ($arr as $item) {
18                $output .= "\t\t<td>$item</td>\r";
19            }
20           
21            $this->output .= "$output\t</tr>\r";
22        } else {
23            $this->output .= "\t<tr>\r\t\t<td>$arr</td>\r\t</tr>\r";
24        }
25    }
26 
27    function addMultiRow($arr)
28    {
29        foreach ($arr as $item) {
30            if (is_array($item)) {
31                $output = "\t<tr>\r";
32               
33                foreach($item as $sItem) {
34                    $output .= "\t\t<td>$sItem</td>\r";
35                }
36                $this->output .= "$output\t</tr>\r";
37            } else {
38                $this->output .= "\t<tr>\r\t\t<td>$item</td>\r\t</tr>\r";
39            }
40        }
41    }
42 
43    function render()
44    {
45        echo $this->output . "</table>";
46    }
47}

Usage:

 1<?php
 2
 3// Get the class (the name may be different)
 4require("Table.class.php");
 5
 6// Load the Table Class
 7$table = new Table();
 8
 9// Adds 1 row and column
10$table->addSingleRow("1 row");
11
12// Adds 1 row and 2 columns
13$table->addSingleRow(["First column", "Second column"]);
14
15// Adds 2 rows with 1 column
16$table->addMultiRow(["First row", "Second row"]);
17
18// Add 2 rows and 2 columns
19$table->addMultiRow([
20    ["First row and column", "second column"],
21    ["Second row and first column", "second column"],
22]);
23
24// Output everything
25echo $table->render();

This is a very simple Table Class because you can’t define attributes like title, class, id, etc. But you are free to use and to change off course :).

~Juje007

© 2026 Jurjen