logo

Creating a Basic Bar Graph using PHP

This tutorial will show you how to create a simple bar graph using PHP. We will use the senario of a business owner wanting to see the total number of sales for the year divided into months. We will then graph all 12 months to see a visual representation of the data.

In this example I will use a array called $month_totals[] that will store the number of sales made in a particular month. The array will have 12 elements. One for each month. We will also setup 2 other variables that will be used to draw the graph. The $highest_number variable will store the index of the $month_sales that has the highest number of orders. The $height_factor will then use the highest number and divide by 100 so we can use the values to determine the bar heights based on a percentage.

Code:

//Initialize variables
$month_totals[13] = 0;
$highest_number = 1;
$height_factor = 0;

Now that the variables are setup, we will now loop through the $month_totals array to find the largest number.

Code:

for ($i = 1l $i<13; $i++)
{

if ($month_totals[$i] > $month_totals[$highest_number])
{
$highest_number = $i;
}
}
$height_factor = $month_totals[$highest_number] / 100;
//if you want to have a graph height of 200px, then change the 100 to 200

Once we have determined the highest value and have our height factor we are ready to get to the guts of the function. The graph is created by mixing HTML with some PHP. It may sound messy, but it's actually pretty easy to read.

Code: (HTML)

<table width="715" height="300" borde="1" cellpadding="4" cellspacing="4">
<tr>
<td height="50" colspan="13"><div align="center">Header</div></td>
</tr>
<tr>
<td width="175" height="175"><div align="center">Left Column</div></td>

<?php
for($i =1; $i<13; $i++)
{
$img_height = $month_totals[$i] / $height_factor;
echo "<td width=\"45px\" valign=\"bottom\"><img src=\"../BarGraphImg.png\" width=\"32\" height=\"" . (int)$img_height . "\" />" . $month_totals[$i] . "</td> \n";
} ?>
<tr><td><div align="center">Key</div></td>
<td height="75" colspan="12"><div align="center">Footer</div></td></tr></table>

You should note that the image file used is a 32 pixel by 1 pixel high image file. You can find the image here.

Once the function is complete you should end up with a graph like the one below. I wanted to show you a bare bones graph so you could see how it functions with out getting over whelmed with extra code. This gives you a solid building block and you can now make it your own. The code will also be included in a link below so you can copy and paste in into your own site.

Bar Graph screen shot

Source Code