Create table rows automatically based on number of columns


/ Published in: PHP
Save to your folder(s)

Let's say you want to show a list of employees, and you want to show 3 on each row, use the script below to accomplish that.


Copy this code and paste it in your HTML
  1. <?php
  2. // My array with employees
  3. // sample purpose only
  4. $arr_array = array();
  5.  
  6. for( $i = 0; $i < 10; $i++ ) {
  7.  
  8. $arr_array[$i] = $i+1;
  9.  
  10. }
  11.  
  12. $columns = 3; // employees pr. row
  13. $amount = count($arr_array); // employees total
  14. $amount_td = $columns * (ceil( $amount / $columns )) - $amount; // empty rows to create
  15. $i = 0;
  16. $j = 1;
  17.  
  18. $output.= '<table cellpadding="50" cellspacing="10" border="1">
  19. <tr>';
  20.  
  21. foreach( $arr_array as $key => $value ) {
  22.  
  23. if ( $i >= $columns ) {
  24. $output .= '</tr><tr>';
  25. $i = 0;
  26. }
  27.  
  28. if ( $j <= $columns ) {
  29.  
  30. $class = 'first';
  31.  
  32. } else if ( (($amount+$amount_td)-$j) < $columns ) {
  33.  
  34. $class = 'last';
  35.  
  36. } else {
  37.  
  38. $class = '';
  39.  
  40. }
  41.  
  42. $output.= '<td class="' . $class . '">' . $value . '</td>';
  43. $i++;
  44. $j++;
  45.  
  46. }
  47.  
  48. for( $i = 0; $i < $amount_td; $i++ ) {
  49. $output.= '<td class="last">&nbsp;</td>';
  50. }
  51.  
  52. $output .= '</tr>
  53. </table>';
  54.  
  55. ?>
  56. <!DOCTYPE html>
  57. <html>
  58. <head>
  59. <meta charset=utf-8 />
  60. <title>Table</title>
  61. </head>
  62. <body>
  63.  
  64. <?php print $output; ?>
  65.  
  66. </body>
  67. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.