1
votes

In PHP I have a list with values ranging from 0 to 1 and everything in between. I want to give each value it's own color.

I want 0 to be green, 0.5 to be black and 1 will be red. A value like 0.1 should still be green but starting to gradient to black a little. A value like 0.6 will be black with a small tint towards red.

I tried using RGB method from: Generate colors between red and green for a power meter?

$R = (255 * $percentage) / 100;
$G = (255 * (100 - $percentage)) / 100 ;
$B = 0;

But this creates a color directly between green and red, and I can't use black in the middle.

I tried the HSL to RGB from: HSL to RGB color conversion

/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param   {number}  h       The hue
* @param   {number}  s       The saturation
* @param   {number}  l       The lightness
* @return  {Array}           The RGB representation
*/
function hslToRgb(h, s, l){
    var r, g, b;

    if(s == 0){
        r = g = b = l; // achromatic
    }else{
        var hue2rgb = function hue2rgb(p, q, t){
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1/6) return p + (q - p) * 6 * t;
            if(t < 1/2) return q;
            if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

But this creates a color from green to white to red. I want it to go from green to black to red. Is there anyway I can get this done?

1
You posted Javascript code for a question tagged with PHP. Are you sure you aren't using Javascript to do this?hRdCoder
Oh yeah, sorry. I just converted it to PHP, same code only the variables are for php now.DijkeMark

1 Answers

1
votes

Something as simple as this should do the trick:

$R = 0;
$G = 0;
$B = 0;

// 255 ÷ 50 = 5.1
if($percentage > 50) {
    $R = 5.1 * ($percentage - 50);
} 
elseif($percentage < 50) {
    $G = 255 - (5.1 * $percentage);
}

EDIT

Note that the elseif/else if will be written differently if you use Javascript or PHP. The current example would work for PHP, as it is what your question was tagged.