Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths in the for loop.
Formatting data and displaying it in a grid format is needed most of the times. PHP developers who are good at coding also face this kind of problem due to lack of html knowledge. Also I have seen many questions at experts exchange who asks for formatting data and dynamically creating table. Most of the times developer stuck at the basic row/column problem.
Let me explain you this concept with example. So lets consider I have to generate a table where each row(horizontal) consists of 3 columns (vertical). Basic html syntax used will be <table> , <tr> (row) , <td> (column).
Basic scenario is as follows:
Input:
$arr = array('a','b','c','d','e','f','g','h','i'); // test array containing 9 elements to be displayed in grid format
Expected output:
--------------
a | b | c |
--------------
d | e | f |
--------------
g | h | i |
--------------
So here is the code to dynamically generate table in php :
<?phpecho "Creating table dynamically";$arr = array('a','b','c','d','e','f','g','h','i'); // test array containing 9 elements to be displayed in grid format$tot_cnt = count($arr); // calculating the count of elements in the array i.e. 9echo "<table border=1><tr>"; // start table and open first rowfor( $i = 0 ; $i < $tot_cnt; $i++){ // In the below if loop a check is performed to see that if 3 columns // are created than close the old row and open new row if($i % 3 == 0 && $i !=0 ){ echo "</tr><tr>"; // closing old row and opening new row } echo "<td>".$arr[$i]."</td>"; // add data in columns}echo "</tr></table>"; // close last row and table?>
So basically the number with which you perform mod(%) operation in crucial. The math here is simple ... the mod(%) operator gives the remainder of the division so say for example 25 % 3 will be 1. hope you are clear with the mod concept if not I have provided a reference urls below you may checkout those.
Hope this helps to most of the php developers searching for formatting data in a table.
References for your help:
If you want to understand how html table works check out this ...
Comments (0)