# PHP chose a hex color on a scale from a value

I'm looking for tips to pick a color from a variable value.
I've got a color scale like this:

As you can see, I've got 3 main colors.
The goal is to convert a variable value to a hexadecimal color, using php.

So in this example (lets name the variable x) :

• if x < -2, return "#FF0000"
• if x > 2, return "#00FF00"
• else estimate the color according to the above scale

This can be done using some simple PHP code.

First we want to find the hex value between FF and 22. If we work in decimals the range is 255 - 31. So when x=0 we want a value of 34 and when x=2 we want a value of 255. To do this we simply take (((255-34)/2)*x)+34 = (110.5*x)+34.

If the variable x is below 0 then the hex number has 4 zeros added to the end, if it is above 0 then it has 2 zeros added either side.

The final PHP code for the above logic is:

`<?php`

``` //Calculate the dec value from 22 to FF \$colourDec = (110.5 * abs(\$x)) + 34; \$colourDec = min(\$colourDec, 255); //Convert to hex \$colourHex = dechex(\$colourDec); if (\$x<0) \$colourCode = "#".\$colourHex."0000"; else if (\$x>0) \$colourCode = "#00".\$colourHex."00"; else \$colourCode = "#222222"; ```

```?> ```

There is probably a much more elegant solution, but this one should work.

I used some functions found here.

```<? function rgb2hex(\$rgb) { \$hex = "#"; \$hex .= str_pad(dechex(\$rgb[0]), 2, "0", STR_PAD_LEFT); \$hex .= str_pad(dechex(\$rgb[1]), 2, "0", STR_PAD_LEFT); \$hex .= str_pad(dechex(\$rgb[2]), 2, "0", STR_PAD_LEFT);```

``` return \$hex; // returns the hex value including the number sign (#) } function hex2rgb(\$hex) { \$hex = str_replace("#", "", \$hex); if(strlen(\$hex) == 3) { \$r = hexdec(substr(\$hex,0,1).substr(\$hex,0,1)); \$g = hexdec(substr(\$hex,1,1).substr(\$hex,1,1)); \$b = hexdec(substr(\$hex,2,1).substr(\$hex,2,1)); } else { \$r = hexdec(substr(\$hex,0,2)); \$g = hexdec(substr(\$hex,2,2)); \$b = hexdec(substr(\$hex,4,2)); } \$rgb = array(\$r, \$g, \$b); //return implode(",", \$rgb); // returns the rgb values separated by commas return \$rgb; // returns an array with the rgb values } //Your limit values and HEX colors \$min = -2; \$max = 2; \$min_hex = "#FF0000"; \$max_hex = "#00FF00"; //Your selection between the limits \$sel = -0.7; //Calculations \$interval = \$max - \$min; \$min_rgb = hex2rgb(\$min_hex); \$max_rgb = hex2rgb(\$max_hex); \$min_rgb_R = \$min_rgb[0]; \$min_rgb_G = \$min_rgb[1]; \$min_rgb_B = \$min_rgb[2]; \$max_rgb_R = \$max_rgb[0]; \$max_rgb_G = \$max_rgb[1]; \$max_rgb_B = \$max_rgb[2]; \$new_rgb_R = \$max_rgb_R - (((\$max_rgb_R - \$min_rgb_R)/\$interval)*(\$max - \$sel)); \$new_rgb_G = \$max_rgb_G - (((\$max_rgb_G - \$min_rgb_G)/\$interval)*(\$max - \$sel)); \$new_rgb_B = \$max_rgb_B - (((\$max_rgb_B - \$min_rgb_B)/\$interval)*(\$max - \$sel)); \$new_rgb = array(\$new_rgb_R,\$new_rgb_G,\$new_rgb_B); \$new_hex = rgb2hex(\$new_rgb); //Show results echo "<div style='background-color:\$min_hex'>(\$min) \$min_hex</div>"; echo "<div style='background-color:\$new_hex'>(\$sel) \$new_hex</div>"; echo "<div style='background-color:\$max_hex'>(\$max) \$max_hex</div>"; ```

```?> ```

Category:php Views:13 Time:2019-01-05
Tags: php colors hex

## Related post

• PHP: Convert shorthand Hex Colors to Regular 2010-03-14

I'm trying to make a function that will take short hand hex color to the long hex color. For example if someone submits "f60" it will convert to "ff6600". I understand I need to repeat each number as itself, but what is the most efficient way to do t

• php mail \$body html template, hiding&showing depending from checkbox value 2013-06-01

I have piece of php mail template which is optional and some users fills additional info, some are not, but if some don't fills it, template goes by email empty with not info from form. \$body = '' here is part which always fillable by user: <span

• PHP How can I get HEX Color code from array of R + G + B? 2011-06-16

I have an array: Array ( [red] => 252 [green] => 168 [blue] => 166 [alpha] => 0 ) It's an output of function imagecolorsforindex. How can I get a HTML code from these elements? For example: #99CCFF --------------Solutions------------- Str

• How to Calculate RGB Hex Color Variations with Javascript/jQuery 2011-03-15

I'm trying to programmatically create some css borders and text-shadows (for a letterpress effect) with jQuery. Given an RGB color value, I'd like to be able to calculate color variations much like 0to255 does. For example, given the color #023f74, h

• convert to 3-digit hex color code 2009-09-22

I've been using 3-digit hex color values in CSS for a long time: #fff, #999, #069, etc. I can see how the repeating letters/numbers are merged to create a 3-digit hex color code, but I don't fully understand the pattern to be able to write a converte

• Function that converts hex color values to an approximate color name? 2010-06-07

I don't suppose anyone knows of a function (PHP, preferably) that can take a hex color code and give an approximate color name for that hex value. I don't need a solution with 100s of colors. Even if it just amounted to the colors white, black, red,

• String formatting for hex colors in Python 2011-07-05

I modified a function from PHP to return a color gradient (http://www.herethere.net/~samson/php/color_gradient/color_gradient_generator.php.txt). I am having issues when returning color hex codes ending in 0s. This is the function: def _get_color(cur

• Converting hex color to RGB and vice-versa 2008-10-18

What is the most efficient way to do this? --------------Solutions------------- Real answer: Depends on what kind of hexadecimal color value you are looking for (e.g. 565, 555, 888, 8888, etc), the amount of alpha bits, the actual color distribution

• Ruby, Generate a random hex color 2009-11-08

How can I generate a random hex color with ruby? --------------Solutions------------- Here's one way: colour = "%06x" % (rand * 0xffffff) You can generate each component independently: r = rand(255).to_s(16) g = rand(255).to_s(16) b = rand(255).to_s(

• How to get hex color value rather than RGB value? 2009-11-16

Using the following jQuery will get the RGB value of an element's background color: \$('#selector').css('backgroundColor'); Is there a way to get the hex value rather than the RGB? --------------Solutions------------- var hexDigits = new Array ("0","1

• Hex colors: Numeric representation for "transparent"? 2009-11-17

I am building a web CMS in which the user can choose colours for certain site elements. I would like to convert all colour values to hex to avoid any further formatting hassle ("rgb(x,y,z)" or named colours). I have found a good JS library for that.

• How can I calculate shades of a given hex color in actionscript 3? 2010-02-13

I need a way to calculate lighter hex color(s) based on a provided one. I realize I could use a color transform, but I need the actual value in order to generate a gradient. Thanks in advance for any help - b --------------Solutions------------- Here

• How do I convert a Hex color to and RGB color using T-SQL 2010-06-21

How do I convert a Hex color to and RGB color using T-SQL --------------Solutions------------- http://odata.stackexchange.com/stackoverflow/q/4813/undefined DECLARE @temp AS TABLE (hex char(6)) INSERT INTO @temp VALUES ('3333CC') -- Should convert to

• Hex color value in objective-c 2010-11-05

I have hex value in mind that I need to implement, working on ipad by the way. Anyways, how can I go about implementing that with objective-c Help much needed, pleas and thank you! --------------Solutions------------- UIColor's range is from 0 to 1.

• Why does WPF use HTML/HEX Colors? 2010-11-11

Why: <Trigger Property="ItemsControl.AlternationIndex" Value="2"> <Setter Property="Background" Value="#FAC896"></Setter> </Trigger> and not: <Trigger Property="ItemsControl.AlternationIndex" Value="2"> <Setter Proper

• What is the easiest way to get a hex color code from a set of color percentages in Objective-c? 2011-02-19

What is the best way to get a hex color code from a set of three RGB percentages? For example: [self getHexFromRed:0.5 Green:0.5 Blue:0.5]; // returns @"7F7F7F" I've found several functions for going the other way (creating a color from a hex code),

• How do I randomly generate HTML hex color codes using JavaScript? 2011-02-23

Possible Duplicate: Random Color generator in Javascript I have some data I'd like to display in different colors and I want to generate the colors randomly if possible. How can I generate the Hex Color Code using JavaScript? --------------Solutions-

• How do UIWebView and UIScrollView manage RGB and hexa Colors? 2011-04-15

I am encountering a strange problem : I added a UIWebView in a UIScrollView. I tried to apply a background color for both. For the UIScrollView I used Interface Builder and I specified a RGB coded color : 255 0 0 (100% red). For the UIWebView I speci

• Ruby, Generate a random hex color (only light colors) 2011-05-31

I know this is possible duplicated question. Ruby, Generate a random hex color My question is slightly different. I need to know, how to generate the random hex light colors only, not the dark. --------------Solutions------------- In this thread colo

• Average 2 hex colors together in javascript 2011-06-16

Alright thought I would throw this one out there for the crowd to think over. Given a function (written in javascript) that expects two strings formated like a hex color (ex #FF0000) return a hex color that is the average of both of the colors passed

• which one is faster: hex color codes or color names? 2011-07-10

I just wanted to know if it's faster to use hex color codes or the color names when I want to use it in CSS? --------------Solutions------------- My guess is the codes will be faster since the names are probably assigned to a look-up table and refere

• Storing hex color values in strings.xml 2011-07-13

I'm trying to store the hex color value of my text in strings.xml so all the layout files will refer to that (to be able to quickly change all layout text for the project easily) however I'm having trouble referring to it. Using android:textColor="#F

• How do I convert a Hex color to VBA color to use in Powerpoint in T-SQL? 2011-08-01

I need to create a function in T-SQL that will take a Hex color and convert it into a color number to use in VBA for Powerpoint. --------------Solutions------------- Here is the correct answer: B*65536 + G*256 + R

• Hex Colors in Android are some times 8 digits. How? 2011-08-02

I sometimes have seen in examples where the coloring in Android is done as #FF191919. I mean a 8 digit hex number . But it should be only a 6 digit number. How are they related? If I want o convert a 6 digit number to a 8 digit number. How to do it?

• Convert hex color value ( #ffffff ) to integer value 2011-08-04

I am receiving hex color values from a server (in this form, #xxxxxx , example #000000 for black) How do I convert this to an integer value? I tried doing Integer.valueOf("0x" + passedColor.substring(1, passedColor.length())) to get an even more hext