Site icon Nabtron

[Solved]How to create a HTML table from PHP array

While working on a project last week I encountered a situation in which an array was supposed to be converted to a HTML table.

Basically I was working on a WordPress plugin and required the array to be dynamic with any number of items and keys in it so hard coding the table structure was out of question.

The trick was, to just get an array out of the database and convert it into a html table, without knowing the size and nature of the data in the array!

This code will work for an array of this sort :

$array = array(
array(‘first’=>’somefirstname’, ‘last’=>’somelastname’, ’email’=>’someemail@somedomain.com’, ‘company’=>’example ltd’),
array(‘first’=>’htmlcoder’, ‘last’=>’phpmaster’, ’email’=>’array@example.org’, ‘company’=>’example ltd’)
);

In this case, where the array is in the above mentioned form, the following code will work to convert this array into an html table (array included within the code)

Please note, if you want to use an array which is mysql SELECT result, you can do that by simply replacing the array with the result generated through your mysql query.

 

<?php
function arraytotable($array){
// start generating table
$html = ‘<table>’;
// generate table heading by using data from first row
$html .= ‘<tr>’;
foreach($array[0] as $key=>$value){
$html .= ‘<th>’ . $key . ‘</th>’;
}
$html .= ‘</tr>’;
// generate table rows from remaining data rows
foreach( $array as $key=>$value){
$html .= ‘<tr>’;
foreach($value as $key2=>$value2){
$html .= ‘<td>’ . $value2 . ‘</td>’;
}
$html .= ‘</tr>’;
}
// finish table code and return it
$html .= ‘</table>’;
return $html;
}
$array = array(
array(‘first’=>’somefirstname’, ‘last’=>’somelastname’, ’email’=>’someemail@somedomain.com’, ‘company’=>’example ltd’),
array(‘first’=>’htmlcoder’, ‘last’=>’phpmaster’, ’email’=>’array@somedomain.com’, ‘company’=>’example ltd’)
);
//show the generated html table to the public
echo arraytotable($array);
?>

 

Exit mobile version