back to home page

PHP Grid Script

Posted on May 17th, 2011

Here is a quick grid script I wrote in PHP, it allows you to generate a tile based grid that has various options. I’m not really going to walk through it the code is self explanatory and easy to use. Here are the buildGrid parameters that it can take to modify the grid.

Doc:
buildGrid(width, height, padding, margin, color, border, dimension)
So here’s the breakdown:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Grid{

   function loadCSS($padding, $margin, $color, $border, $dimension)
   {
      echo  '<style>
               #canvas p
               {
                  clear: both;
                  width: 100%;
                  margin: 0;
               }
               #canvas span
               {
                  float: left;
               }
               #canvas span.tile
               {
                  width: '
.$dimension.'px;
                  height: '
.$dimension.'px;
                  background: #'
.$color.';';
                  if($border){
                      echo 'border: 1px #000 solid;';
                  }
                  echo 'padding:'.$padding.'px;
                  margin:'
.$margin.'px;
               }
            </style>'
;
   }
   
   function buildGrid($width, $height, $padding=5, $margin=2, $color='06D606', $border=true, $dimension=50)
   {
      $this->loadCSS($padding, $margin, $color, $border, $dimension);
      echo '<div id="canvas">';
      echo '<span class="canvas">';
      for($row=0;$row < $width;$row++){
         echo '<p>';
         for($column=0; $column < $height;$column++){
            echo '<span class="tile">'.$row.', '.$column.'</span>';
         }
         echo '</p>';
      }
      echo '</span></div>';
   }
}

Usage:

1
2
$testGrid = new Grid();
$testGrid->buildGrid(5,5);

This little script is licensed under WTFPL and is available on snipt here!

1
2
3
4
5
6
7
8
9
10
11
12
13
            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.

Hopefully this helps someone out at anything they may need a grid for.

If anyone request or finds this snippet helpful I will follow up with another tutorial that shows how to dynamically load content into a specific tile.


Leave a Reply

    To syntax highlight code just use [cc lang="whatever language here"]your code here[/cc]