Php > Graphics Code Examples

Simple bar graph

``` Simple bar graph When you want to compare your data among durations, the first choice is graph. This function will create a bar graph by using only tag table. If your data looks like this: Month 1 Growth 25% Month 2 Growth 20% Month 4 Growth 15% Month 7 Growth 23% select all data to array: \$dnum[1]=25, \$dnum[2]=20, \$dnum[4]=15, \$dnum[7]=23 and \$allmonth=7 that means you have data until 7th month then send variable to function graph() <? \$dnum[1]=25; \$dnum[2]=20; \$dnum[4]=15; \$dnum[7]=23; \$allmonth=7; function graph(\$allmonth, \$dnum) { \$maxdnum=ceil(max(\$dnum)); //find out the maximal value of array if (\$maxdnum>=50) { \$xnum=1; } //set scale of graph to 100% elseif (\$maxdnum>=20) { \$xnum=2; } //set scale of graph to 50% elseif (\$maxdnum>=10) { \$xnum=5; } //set scale of graph to 20% elseif (\$maxdnum>=5) { \$xnum=10; } //set scale of graph to 10% elseif (\$maxdnum>=0) { \$xnum=20; } //set scale of graph to 5% echo "<br><table align=center width=100% border=1>"; echo "<tr bgcolor=cyan align=center><td>Month</td>"; for (\$i=1; \$i<=100; \$i++) { echo "<td></td>"; } echo "<td>%</td></tr>"; for (\$k=1; \$k<=\$allmonth; \$k++) { if ( !isset(\$dnum[\$k]) ) { \$dnum[\$k]='NA'; } //set value to missed month echo "<tr align=center><td>\$k</td>"; if (\$dnum[\$k] !='NA') { \$dgraph[\$k]=round(\$dnum[\$k]*\$xnum); \$rgraph=100-\$dgraph[\$k]; } else { \$dgraph[\$k]=0; \$rgraph=100; } for (\$i=1; \$i<=\$dgraph[\$k]; \$i++) { echo "<td bgcolor=red></td>"; } for (\$j=1; \$j<=\$rgraph; \$j++) { echo "<td bgcolor=#dedede></td>"; } echo "<td>\$dnum[\$k]</td></tr>"; } echo "</table>"; } // Usage : // graph(\$allmonth,\$dnum); ?> ```