Use at own risk. Programs haven't been thoroughly tested.

function: color_status

Returns a HTML color between green and red Takes 1 integer between 0 (green-est) and 100 (red-est) as a parameter and returns a valid Heximal color code. Very Usefull if you want to create status colors to visually inform users of what is happening.

Info

@author Kevin van Zonneveld
@version 1.0
@link http://kevin.vanzonneveld.net
@param (string/int) $percentage A value between 1 and 100, typically a percentage of something. Can also be a string like: "25/100", saying: 25(value) out of 100(max).

Example

Usage
echo "<span style='color:".color_status(50).";'>50%</span>";

Outputs
50%

Source Code

download source
<?
function color_status($percentage=1){
  
 
  // determine the percentage, maybe we were told to do
    // calculate the percentage
  if(substr_count($percentage,"/")){
    list($v,$m) = explode("/",$percentage);
    if($m == 0){
      $percentage = 0;
    } else{
      $percentage = ($v / $m * 100);
    }
  }
 
    // force the percentage between 1 and 100
  if($percentage > 100){$percentage=100;}
  if($percentage < 1){$percentage=1;}
 
    // scale the percentage to make it the HUE of a color
  $factor = (100 / $percentage);
  $percentage = 87 - intval(87 / $factor);
 
    // we want an RGB value of the following HSV color
  $h = $percentage;
  $s = 255;
  $v = 255;
 
  // HSV 2 RGB
  $s /= 256.0;
  $v /= 256.0;
  if ( $s == 0.0 ){
    $r = $g = $b = $v;
    return '';
  } else {
    $h = $h/256.0*6.0;
    $i = floor($h);
    $f = $h - $i;
 
    $v *= 256.0;
    $p = (integer)($v * (1.0 - $s));
    $q = (integer)($v * (1.0 - $s * $f));
    $t = (integer)($v * (1.0 - $s * (1.0 - $f)));
    switch( $i ) {
      case 0:
        return "#".sprintf('%02X%02X%02X',$v,$t,$p);
      break;
      case 1:
        return "#".sprintf('%02X%02X%02X',$q,$v,$p);
      break;
      case 2:
        return "#".sprintf('%02X%02X%02X',$p,$v,$t);
      break;
      case 3:
        return "#".sprintf('%02X%02X%02X',$p,$q,$v);
      break;
      case 4:
        return "#".sprintf('%02X%02X%02X',$t,$p,$v);
      break;
      default:
        return "#".sprintf('%02X%02X%02X',$v,$p,$q);
      break;
    }
  }
}
?>

Add comment

» Currently away on vacation. I can reply your message the 24th of July 2008. Please post anyway and check back then. Thank you!

for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

Comments

No comments. Be the first!