46

How do I create a HTML table from a PHP array? A table with heading as 'title', 'price', and 'number'.

$shop = array(
    array("rose",   1.25, 15),
    array("daisy",  0.75, 25),
    array("orchid", 1.15, 7 ),
); 
hakre
  • 193,403
  • 52
  • 435
  • 836
ktm
  • 6,025
  • 24
  • 69
  • 95
  • 4
    This is the exact same question as http://stackoverflow.com/questions/4746079/how-do-i-create-table-with-this-php-array Please do not double post questions - you're just wasting your own (and everybody else's) time. – John Parker Jan 20 '11 at 18:15
  • 5
    Merged. And, pray I do not merge again! –  Jan 20 '11 at 18:40
  • This thread has been answered here [Click here](https://stackoverflow.com/questions/4746079/how-to-create-a-html-table-from-a-php-array/47068295#47068295) – Delickate Nov 02 '17 at 06:08

18 Answers18

92

It would be better to just fetch the data into array like this:

<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
               array("title"=>"daisy", "price"=>0.75 , "number"=>25),
               array("title"=>"orchid", "price"=>1.15 , "number"=>7) 
             ); 
?>

And then do something like this, which should work well even when you add more columns to your table in the database later.

<?php if (count($shop) > 0): ?>
<table>
  <thead>
    <tr>
      <th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
    </tr>
  </thead>
  <tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
    <tr>
      <td><?php echo implode('</td><td>', $row); ?></td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>
Jordan Arsenault
  • 7,100
  • 8
  • 53
  • 96
Richard Knop
  • 81,041
  • 149
  • 392
  • 552
  • 1
    Smart way to create a table. I have created a useful function based on your code. Thx – sdespont Feb 03 '14 at 10:59
  • 3
    array_map() returns an array, and $row is not passed by reference so that line essentially does nothing, no? – syaz Feb 08 '15 at 20:14
  • 1
    can someone explain about array_map('htmlentities', $row) ? i dont understand – Galang Re Feb 05 '18 at 07:06
  • @GalangRe htmlentities() is just making sure that a value can be displayed and won't break HTML code. array_map() is a php function to apply a function to every element of an array. So in combination this will make sure all values are HTML save. However: I strongly urge you to not code like this, that's how PHP started in 1994 and it's absolutely ugly, unmanageable and hell of a nightmare to collaborate with. DO NOT mix PHP code and output. DO NOT switch on/off the PHP interpreter. – John Nov 27 '18 at 04:47
  • @John all answers here do mix php code and html output. How would you do it? – Timo Mar 06 '22 at 21:47
  • I use your code to `fetchall()` from a mysql table. I get each columname which is good and also get each column index which is not good. How can I avoid the indexcolumn? – Timo Mar 07 '22 at 09:44
  • @john maybe you are out for Frameworks to separate the view from the controller. – Timo Mar 07 '22 at 09:45
  • 2
    @Timo A view/controller type framework is nice for medium to large projects (Twig is a great language and tool for that). For smaller projects it's fine to mix the code in my opinion but NEVER touch the "?>" feature, never switch off the php interpreter. You'll end with embarrassing spaghetti code. When employing, such code is a reason for me to reject a person without further questions. – John Mar 07 '22 at 22:08
  • @john how would you then code the example of this answer without mixing php and html? – Timo Mar 08 '22 at 10:39
  • 2
    @timo just do not turn off the PHP interpreter, that's extremely ugly scripting from 1994 times. Just make a function that outputs the HTML (echo) or put echo into your code. If your project grows bigger use something like twig. – John Mar 09 '22 at 14:17
  • @John with all due respect, echoing HTML from your code is uglier than breaking out of the interpreter. Most modern IDEs can (or should be able to) parse correctly in both modes. HTML embedded in strings not so much. One of the first things I do with spaghetti is pull the HTML out so it can be validated and balanced, and it's much easier to inspect. Of course, depending on the project, the next thing is replace it with generators or templates, I agree with you on the separation. – Duncan Dec 07 '22 at 02:52
  • @Duncan I neither employ nor tolerate any freelancers who do that in any part of a php project, but yes you can do it in an ugly way you can also do it in a very clean way. PHP has evolved extremely since the first days, it changed from a hacky script language into a programming language (actually one of the fastest interpreters out there, right next after javascript) – John Dec 24 '22 at 01:05
41

Here's mine:

<?php
    function build_table($array){
    // start table
    $html = '<table>';
    // header row
    $html .= '<tr>';
    foreach($array[0] as $key=>$value){
            $html .= '<th>' . htmlspecialchars($key) . '</th>';
        }
    $html .= '</tr>';

    // data rows
    foreach( $array as $key=>$value){
        $html .= '<tr>';
        foreach($value as $key2=>$value2){
            $html .= '<td>' . htmlspecialchars($value2) . '</td>';
        }
        $html .= '</tr>';
    }

    // finish table and return it

    $html .= '</table>';
    return $html;
}

$array = array(
    array('first'=>'tom', 'last'=>'smith', 'email'=>'tom@example.org', 'company'=>'example ltd'),
    array('first'=>'hugh', 'last'=>'blogs', 'email'=>'hugh@example.org', 'company'=>'example ltd'),
    array('first'=>'steph', 'last'=>'brown', 'email'=>'steph@example.org', 'company'=>'example ltd')
);

echo build_table($array);
?>
Community
  • 1
  • 1
19
   <table>
     <tr>
       <td>title</td>
       <td>price</td>
       <td>number</td>
     </tr>
     <? foreach ($shop as $row) : ?>
     <tr>
       <td><? echo $row[0]; ?></td>
       <td><? echo $row[1]; ?></td>
       <td><? echo $row[2]; ?></td>
     </tr>
     <? endforeach; ?>
   </table>
bassneck
  • 4,053
  • 4
  • 24
  • 32
15

You can also use array_reduce

array_reduce — Iteratively reduce the array to a single value using a callback function

example:

$tbody = array_reduce($rows, function($a, $b){return $a.="<tr><td>".implode("</td><td>",$b)."</td></tr>";});
$thead = "<tr><th>" . implode("</th><th>", array_keys($rows[0])) . "</th></tr>";

echo "<table>\n$thead\n$tbody\n</table>";
papo
  • 1,606
  • 19
  • 18
Dmitriy
  • 386
  • 2
  • 5
  • 1
    even though this is just on three lines, it's a cleanest solution in a sense that it uses appropriate PHP constructs for the job. – papo Feb 04 '19 at 16:19
8

This is one of de best, simplest and most efficient ways to do it. You can convert arrays to tables with any number of columns or rows. It takes the array keys as table header. No need of array_map.

function array_to_table($matriz) 
{   
   echo "<table>";

   // Table header
        foreach ($matriz[0] as $clave=>$fila) {
            echo "<th>".$clave."</th>";
        }

    // Table body
       foreach ($matriz as $fila) {
           echo "<tr>";
           foreach ($fila as $elemento) {
                 echo "<td>".$elemento."</td>";
           } 
          echo "</tr>";
       } 
   echo "</table>";}
IntelarX
  • 131
  • 1
  • 4
5
echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
    echo "<tr>";
    foreach($v as $vv){
        echo "<td>{$vv}</td>";
    }
    echo "<tr>";
}
echo "</table>";
Mike Valstar
  • 3,499
  • 5
  • 24
  • 32
4
echo '<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>';
foreach($shop as $id => $item) {
    echo '<tr><td>'.$item[0].'</td><td>'.$item[1].'</td><td>'.$item[2].'</td></tr>';
}
echo '</table>';
Angelo R.
  • 2,285
  • 1
  • 17
  • 22
3

Here is my answer.

function array2Html($array, $table = true)
{
    $out = '';
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            if (!isset($tableHeader)) {
                $tableHeader =
                    '<th>' .
                    implode('</th><th>', array_keys($value)) .
                    '</th>';
            }
            array_keys($value);
            $out .= '<tr>';
            $out .= array2Html($value, false);
            $out .= '</tr>';
        } else {
            $out .= "<td>".htmlspecialchars($value)."</td>";
        }
    }

    if ($table) {
        return '<table>' . $tableHeader . $out . '</table>';
    } else {
        return $out;
    }
}

However, your table headers have to be a part of the array, which is pretty common when it comes from a database. e.g.

$shop = array(
    array(
        'title' => 'rose',
        'price' => 1.25,
        'number' => 15,
    ),
    array(
        'title' => 'daisy',
        'price' => 0.75,
        'number' => 25,
    ),
    array(
        'title' => 'orchid',
        'price' => 1.15,
        'number' => 7,
    ),
);

print array2Html($shop);

Hope it helps ;)

Timo Huovinen
  • 53,325
  • 33
  • 152
  • 143
frenus
  • 481
  • 4
  • 9
  • you forgot to htmlspecialchars encode your str, so data should be encoded unless you pass it an option not to encode it – Timo Huovinen Mar 01 '16 at 13:55
  • I got 3 issues, first is I get same result as [above](https://stackoverflow.com/questions/4746079/how-to-create-a-html-table-from-a-php-array#comment126166401_4747673), second is how is recursion working here? Where is the recursion break? I think the two returns are the break, the function is finally run with $table true not looping and returns the table. Third is minor error in your code, fix the calling name of the function. – Timo Mar 07 '22 at 10:52
  • @TimoHuovinen maybe you can help as well regarding my comment. – Timo Mar 07 '22 at 10:58
3
    <table>
      <thead>
        <tr><th>title</th><th>price><th>number</th></tr>
      </thead>
      <tbody>
<?php
  foreach ($shop as $row) {
    echo '<tr>';
    foreach ($row as $item) {
      echo "<td>{$item}</td>";
    }
    echo '</tr>';
  }
?>
      </tbody>
    </table>
Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
2

You may use this function. To add table header you can setup a second parameter $myTableArrayHeader and do the same with the header information in front of the body:

function insertTable($myTableArrayBody) {
    $x = 0;
    $y = 0;
    $seTableStr = '<table><tbody>';
    while (isset($myTableArrayBody[$y][$x])) {
        $seTableStr .= '<tr>';
        while (isset($myTableArrayBody[$y][$x])) {
            $seTableStr .= '<td>' . $myTableArrayBody[$y][$x] . '</td>';
            $x++;
        }
        $seTableStr .= '</tr>';
        $x = 0;
        $y++;
    }
    $seTableStr .= '</tbody></table>';
    return $seTableStr;
}
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
2

PHP code:

$multiarray = array (

    array("name"=>"Argishti", "surname"=>"Yeghiazaryan"),
    array("name"=>"Armen", "surname"=>"Mkhitaryan"),
    array("name"=>"Arshak", "surname"=>"Aghabekyan"),

);

$count = 0;

foreach ($multiarray as $arrays){
    $count++;
    echo "<table>" ;               

    echo "<span>table $count</span>";
    echo "<tr>";
    foreach ($arrays as $names => $surnames){

        echo "<th>$names</th>";
        echo "<td>$surnames</td>";

    }
    echo "</tr>";
    echo "</table>";
}

CSS:

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;``
}
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
2

Build two foreach loops and iterate through your array. Print out the value and add HTML table tags around that.

Tobias
  • 7,238
  • 10
  • 46
  • 77
1

I had a similar need, but my array could contain key/value or key/array or array of arrays, like this array:

$array = array(
    "ni" => "00000000000000",
    "situacaoCadastral" => array(
        "codigo" => 2,
        "data" => "0000-00-00",
        "motivo" => "",
    ),
    "naturezaJuridica" => array(
        "codigo" => "0000",
        "descricao" => "Lorem ipsum dolor sit amet, consectetur",
    ),
    "dataAbertura" => "0000-00-00",
    "cnaePrincipal" => array(
        "codigo" => "0000000",
        "descricao" => "Lorem ips",
    ),
    "endereco" => array(
        "tipoLogradouro" => "Lor",
        "logradouro" => "Lorem i",
        "numero" => "0000",
        "complemento" => "",
        "cep" => "00000000",
        "bairro" => "Lorem ",
        "municipio" => array(
            "codigo" => "0000",
            "descricao" => "Lorem ip",
        ),
    ),
    "uf" => "MS",
    "pais" => array(
        "codigo" => "105",
        "descricao" => "BRASIL",
    ),
    "municipioJurisdicao" => array(
        "codigo" => "0000000",
        "descricao" => "DOURADOS",
    ),
    "telefones" => array(
        array(
            'ddd' => '67',
            'numero' => '00000000',
        ),
    ),
    "correioEletronico" => "lorem@ipsum-dolor-sit.amet",
    "capitalSocial" => 0,
    "porte" => "00",
    "situacaoEspecial" => "",
    "dataSituacaoEspecial" => ""
);

The function I created to solve was:

function array_to_table($arr, $first=true, $sub_arr=false){
    $width = ($sub_arr) ? 'width="100%"' : '' ;
    $table = ($first) ? '<table align="center" '.$width.' bgcolor="#FFFFFF" border="1px solid">' : '';
    $rows = array();
    foreach ($arr as $key => $value):
        $value_type = gettype($value);
        switch ($value_type) {
            case 'string':
                $val = (in_array($value, array(""))) ? "&nbsp;" : $value;
                $rows[] = "<tr><td><strong>{$key}</strong></td><td>{$val}</td></tr>";
                break;
            case 'integer':
                $val = (in_array($value, array(""))) ? "&nbsp;" : $value;
                $rows[] = "<tr><td><strong>{$key}</strong></td><td>{$value}</td></tr>";
                break;
            case 'array':
                if (gettype($key) == "integer"):
                    $rows[] = array_to_table($value, false);
                elseif(gettype($key) == "string"):
                    $rows[] = "<tr><td><strong>{$key}</strong></td><td>".
                        array_to_table($value, true, true) . "</td>";
                endif;
                break;
            default:
                # code...
                break;
        }
    endforeach;
    $ROWS = implode("\n", $rows);
    $table .= ($first) ? $ROWS . '</table>' : $ROWS;
    return $table;
}

echo array_to_table($array);

And the output is this

eberblk kk
  • 11
  • 4
0

Array into table. Array into div. JSON into table. JSON into div.

All are nicely handle this class. Click here to get a class

How to use it?

Just get and object

$obj = new Arrayinto();

Create an array you want to convert

$obj->array_object = array("AAA" => "1111",
                  "BBB" => "2222",
                  "CCC" => array("CCC-1" => "123",
                                 "CCC-2" => array("CCC-2222-A" => "CA2",
                                                  "CCC-2222=B" => "CB2"
                                                 )
                                )

                 );

If you want to convert Array into table. Call this.

$result = $obj->process_table();

If you want to convert Array into div. Call this.

$result = $obj->process_div();

Let suppose if you have a JSON

$obj->json_string = '{
            "AAA":"11111",
            "BBB":"22222",
            "CCC":[
                    {
                        "CCC-1":"123"
                    },
                    {
                        "CCC-2":"456"
                    }
                  ] 
         }
        ';

You can convert into table/div like this

$result = $obj->process_json('div');

OR

$result = $obj->process_json('table');
Dharman
  • 30,962
  • 25
  • 85
  • 135
Delickate
  • 1,102
  • 1
  • 11
  • 17
0
<?php

echo "<table>
<tr>
<th>title</th>
<th>price</th>
<th>number</th>
</tr>";
for ($i=0; $i<count($shop, 0); $i++)
{
    echo '<tr>';
    for ($j=0; $j<3; $j++)
    {
        echo '<td>'.$shop[$i][$j].'</td>';
    }
    echo '</tr>';
}
echo '</table>';

You can optimize it, but that should do.

animuson
  • 53,861
  • 28
  • 137
  • 147
zozo
  • 8,230
  • 19
  • 79
  • 134
0

You can use foreach to iterate the array $shop and get one of the arrays with each iteration to echo its values like this:

echo '<table>';
echo '<thead><tr><th>title</td><td>price</td><td>number</td></tr></thead>';
foreach ($shop as $item) {
    echo '<tr>';
    echo '<td>'.$item[0].'</td>';
    echo '<td>'.$item[1].'</td>';
    echo '<td>'.$item[2].'</td>';
    echo '</tr>';
}
echo '</table>';
Fadupla
  • 13
  • 1
  • 5
Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

this will print 2-dimensional array as table.

First row will be header.

function array_to_table($table) 
{   
    echo "<table>";

    // Table header
    foreach ($table[0] as $header) {
      echo "<th>".$header."</th>";
    }

    // Table body
    $body = array_slice( $table, 1, null, true);
    foreach ($body as $row) {
      echo "<tr>";
        foreach ($row as $cell) {
          echo "<td>".$cell."</td>";
        } 
      echo "</tr>";
    }     
  echo "</table>";
}

usage:

arrayOfArrays = array(
    array('header1',"header2","header3"),
    array('1.1','1.2','1.3'),
    array('2.1','2.2','2.3'),
);


array_to_table($arrayOfArrays);

result:

<table><tbody><tr><th>header1</th><th>header2</th><th>header3/th><tr><td>1.1</td><td>1.2</td><td>1.3</td></tr><tr><td>2.1</td><td>2.2</td><td>2.3</td></tr><tr><td>3.1</td><td>3.2</td><td>3.3</td></tr></tbody></table>
Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101
0

Here is the more generic version of @GhostInTheSecureShell 's answer.

<?php
function build_tabular_format($items)
{
    $html = '';
    $items_chunk_array = array_chunk($items, 4);
    foreach ($items_chunk_array as $items_single_chunk)
    {
        $html .= '<div class="flex-container">';
        foreach ($items_single_chunk as $item)
        {
            $html .= '<div class="column-3">';
            $html .= $item['fields']['id'];
            $html .= '</div>';
        }
        $html .= '</div>';
    }
    return $html;
}

$items = array(
    array(
        'fields' => array(
            'id' => '1',
        ) ,
    ) ,
    array(
        'fields' => array(
            'id' => '2',
        ) ,
    ) ,
    array(
        'fields' => array(
            'id' => '3',
        ) ,
    ) ,
    array(
        'fields' => array(
            'id' => '4',
        ) ,
    ) ,

    array(
        'fields' => array(
            'id' => '5',
        ) ,
    ) ,
    array(
        'fields' => array(
            'id' => '6',
        ) ,
    ) ,
    array(
        'fields' => array(
            'id' => '7',
        ) ,
    ) ,
    array(
        'fields' => array(
            'id' => '8',
        ) ,
    ) ,
);

echo build_tabular_format($items);
?>

The output will be like:

<div class="flex-container">
    <div class="column-3">1</div>
    <div class="column-3">2</div>
    <div class="column-3">3</div>
    <div class="column-3">4</div>
</div>
<div class="flex-container">
    <div class="column-3">5</div>
    <div class="column-3">6</div>
    <div class="column-3">7</div>
    <div class="column-3">8</div>
</div>
Pavan Yogi
  • 180
  • 2
  • 7