Array To Tablerows


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



Copy this code and paste it in your HTML
  1. // Example Usage: array_to_tablerows(array('x', 'x', 'x', 'x', 'x', 'x'), 4);
  2. // Returns: <tr><td>X</td><td>X</td><td>X</td><td>X</td></tr><tr><td>X</td><td>X</td><td colspan="2">&nbsp;</td></tr>
  3. // Table with 4 columns with 6 values from left to right.
  4.  
  5. function array_to_tablerows($array = array(), $columns = 2) {
  6. if (!is_array($array) || $columns < 1) return false;
  7. $table = '<tr>';
  8. $i = 1;
  9. $array_length = count($array);
  10. foreach ($array as $v) {
  11. $remainder = $i % $columns;
  12. $table .= "<td>$v</td>";
  13. if ($i == $array_length) {
  14. $table .= ($remainder ? ('<td colspan="' . abs($columns - $remainder) . '">&nbsp;</td>') : '') . '</tr>';
  15. }
  16. elseif ($remainder == 0) {
  17. $table .= '</tr><tr>';
  18. }
  19. ++$i;
  20. }
  21. return $table;
  22. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.