Colum-focused Tables

A client wanted to add some equipment pages, where each item is listed as an image, its name, and its price. These are listed vertically, meaning that in each row of items, I have to insert all the images, then all the names, then all the prices. Obviously, that's not the best way to deal with things, is it? So I put together a fairly small - but not simple - script which generates the tables for you. The code is free, and the changes are fairly straightforward.

function addItem($location, $name, $price) { // This function created by Michael Diamond - // For licensing information visit // Insert parameter modifications here $location = '<img src="'.$location.'" alt="'.$name.'" />'; $price = '$'.$price; // paste the parapeter list into the array parentheses global $equipmentItems; $equipmentItems[] = array($location, $name, $price); } function outputItemTable($colums = 3) { // This function created by Michael Diamond - // For licensing information visit global $equipmentItems; $numItems = count($equipmentItems); $subItems = count($equipmentItems[0]); $rows = $numItems % $colums == 0 ? $numItems / $colums : $numItems / $colums + 1; $firstItemInRow = 0; $output = '<table class="equipmentTable">'; for($currentItem = 0; $currentItem < $numItems; $firstItemInRow += $colums) { for($subItem = 0; $subItem < $subItems; $subItem++) { $output .= "<tr>\n"; for($col = 0, $currentItem = $firstItemInRow; $col < $colums; $col++, $currentItem++) { if($col >= $numItems) break; if($currentItem >= $numItems) { $output .= '<td> </td>'; continue; } $output .= '<td>'.$equipmentItems[$currentItem][$subItem].'</td>'; } $output .= "\n</tr>"; } } echo $output.'</table>'; $equipmentItems = array(); } // Example - this will output a two by two table of items: addItem('/img/img1.jpg', 'The Image', 400.30); addItem('/img/img2.jpg', 'The Other Image', 12.50); addItem('/img/img3.jpg', 'The New Image', 96.75); addItem('/img/img4.jpg', 'The Last Image', 234.99); outputItemTable(2);


You only need to modify the function addItem() in three ways:

  • Modify the parameters of the function to take each item you want.
  • If you want anything other than the raw text to be output (for instance images) modify the variables in the body of the function.
  • Insert the parameters into the array which will be passed to the next function.

Then look at the example code - call addItem for each item you want to display, in the order, left to right, that you want items to appear, and then call outputItemTable with the number of columns you want.

Questions, comments, or suggestions? Go ahead and Contact Me