-2

I have some code that I got from here: Color coding based on number

function GreenYellowRed($number) {
  $number--; // working with 0-99 will be easier

  if ($number < 50) {
    // green to yellow
    $r = floor(255 * ($number / 50));
    $g = 255;

  } else {
    // yellow to red
    $r = 255;
    $g = floor(255 * ((50-$number%50) / 50));
  }
  $b = 0;

  return "$r,$g,$b";
}

I am then calling it on a percentage output... like this:

"<span style='background-color: rgb(" . GreenYellowRed($percentage) . ")'>" . $percentage . "%</span>"

It works as expected, but it makes lower numbers green and higher numbers red. In my case, low percentage is bad and high percentage is good, but I can't work out what to change to make it work in reverse so that hight numbers go green and low numbers go red.

I've tried a few things but it never seems to do what I want... can anyone help?

Community
  • 1
  • 1
Blind Trevor
  • 746
  • 2
  • 9
  • 28

2 Answers2

1

Chnge this:

return "$r,$g,$b";

to this:

return "$g,$r,$b";
CodeGodie
  • 12,116
  • 6
  • 37
  • 66
-2

Soooo easy when I thought about it!!

All I had to do was to swap $r and $g on each side of the if statement, like this:

function GreenYellowRed($number)
            {
                $number--; // working with 0-99 will be easier

                if ($number < 50) {
                // green to yellow
                $g = floor(255 * ($number / 50));
                $r = 255;

                } else {
                // yellow to red
                $g = 255;
                $r = floor(255 * ((50-$number%50) / 50));
                }
                $b = 0;

                return "$r,$g,$b";
            }

All sorted :)

Blind Trevor
  • 746
  • 2
  • 9
  • 28