Home » HTML, PHP

Creating dynamic table in PHP : Easy and Simple tutorial

9 December 2007 Share/Bookmark

Problem:

I want to create a dynamic table with a row starting after certain number of columns, i.e. like, i want to create an html table which automatically generate new row after 3 columns in a row.

Solution:

$content = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
<table border="1" width="50%">
<tr>
	<?php 
	$counter = 0;
	foreach($content as $data) {
		if($counter != 0 && $counter%3 == 0) {
			?>
			</tr><tr>
			<?php 
		}
		?>
		<td>
			<?php echo $data; ?>
		</td>
		<?php
		$counter++;
	} 
?>
</tr>
</table>

Here, $content is an array of 9 numbers (1 to 9). The array value can be any. You can have your custom array with your custom values. I have looped through the array and printed data in a html table. I have created new row after 3 columns have been created.

Happy PHPing!

From Mukesh Chapagain's Blog, post Creating dynamic table in PHP : Easy and Simple tutorial

email

php magento mukesh chapagain

Get New Post by Email
RSS Feed Subscribe RSS Feed
  • Yrollgayanth

    Thanks a lot, this is very useful

  • Stergios

    Actually does not work very well for all cases. Need to create empty rows .
    Test your code for 4 columns