phpbargraphexample1

PHP bar graph script

It’s time for another code freebie from yours truly.
This is a little script that creates bar graphs with a length and title you specify.


As many as you want, for whatever you want. Like breakfast!


I made the design in Excel 2007 and copied it over to Adobe Fireworks, keeping even the transparency, where I resized it and cut it into pieces. If you want to use my design you can grab the CSS and from there find the URLs to the PNGs.

Do note that the colored part is not to the pixel precise the value you give it. That was impossible, to have the 3d effect in the graphics they obviously had to be wider than 1px, which means we give up some accuracy by not measuring in the width of the graphics. This is most noticeable when you compare 0 (empty) to 1 and 99 to 100 (full), but for non-scientific purposes it should do fine.

Download bargraph.php
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
45
<?php
function bargraph ( $rating=0, $title='' )
{
	// maximum free width (excl. switch)
	$size['max'] = 535;
	// switch width (for exceptions)
	$size['switch'] = 13;
	// some maths
	$size['fill'] = $rating * ( $size['max']/100 );
	$size['fill'] = round( $size['fill'], 0 );
	$size['empty'] = $size['max'] - $size['fill'];
	//
	$result = '';
	$result .= '<div class="bargraph">'."\r\n";
	$result .= '	<h4>'.$title.'</h4>'."\r\n";
	// decide if we have an exception
	switch ( $rating )
	{
		// rating of 0, we'll have to end empty
		case 0:
			$size['empty'] = $size['empty'] + $size['switch'];
			$result .= '	<div class="empty_start"></div>
	<div class="empty" style="width:'.$size['empty'].'px;"></div>
	<div class="empty_end"></div>'."\r\n";
			break;
		// rating of 100, we'll have to start filled
		case 100:
			$size['fill'] = $size['fill'] + $size['switch'];
			$result .= '	<div class="filled_start"></div>
	<div class="filled" style="width:'.$size['fill'].'px;"></div>
	<div class="filled_end"></div>'."\r\n";
			break;
		// rating somewhere in betweeen, start empty, switch and end filled
		default:
			$result .= '	<div class="filled_start"></div>
	<div class="filled" style="width:'.$size['fill'].'px;"></div>
	<div class="switch"></div>
	<div class="empty" style="width:'.$size['empty'].'px;"></div>
	<div class="empty_end"></div>'."\r\n";
			break;
	}
	$result .= '</div>'."\r\n";
	echo $result;
}
?>
Download howtouse.php
1
<?php bargraph(75,'INSERTTITLE'); ?>

If you like it please leave a comment below. I’ve just installed Disqus so your comments will be in good hands.