[thelist] dynamic verticle bar in PHP (table)

Simon Willison cs1spw at bath.ac.uk
Thu Oct 2 03:52:02 CDT 2003


Roger Harness wrote:
> I'd like to have a simple table, 1 cell wide, but 10 cells high.
> 
> Using PHP, is there a way to dynamically change the background of a specific
> cell, and also all cells below that one?
> 
> So if my result was the number 4, the bottom four cells (rows) would have a
> green background, while the top six would have no background. If my number
> was 2, then only the bottom two cells would have the green background.

Here's a function to generate such a thing. It takes two arguments - the 
height of the overall table and the number to be represented. It returns 
the HTML for the table. The table is styled using CSS.

=======

<style type="text/css">
table.barchart {
   width: 100px;
   border: 1px solid black;
}
table.barchart td.filled {
   background-color: green;
}
</style>

<?php

function barChartTable($height, $value) {
     $html = "<table class=\"barchart\">\n";
     for ($i = 0; $i < $height; $i++) {
         if ($i >= ($height - $value)) {
             $class = 'filled';
         } else {
             $class = 'blank';
         }
         $html .= "  <tr><td class=\"$class\">&nbsp;</td></tr>\n";
     }
     $html .= '</table>';
     return $html;
}

print barChartTable(10, 4);

?>

=======

The above code produces the following:

<table class="barchart">
   <tr><td class="blank">&nbsp;</td></tr>
   <tr><td class="blank">&nbsp;</td></tr>
   <tr><td class="blank">&nbsp;</td></tr>
   <tr><td class="blank">&nbsp;</td></tr>
   <tr><td class="blank">&nbsp;</td></tr>
   <tr><td class="blank">&nbsp;</td></tr>
   <tr><td class="filled">&nbsp;</td></tr>
   <tr><td class="filled">&nbsp;</td></tr>
   <tr><td class="filled">&nbsp;</td></tr>
   <tr><td class="filled">&nbsp;</td></tr>
</table>

Hope that helps,

Simon Willison
http://simon.incutio.com/



More information about the thelist mailing list