# 255255255 to #FFFFFF Conversion in PHP



## takua108 (Jan 4, 2006)

Hey, I'm making a website for a game, and the game stores a user's color in a MySQL table as RRRGGGBBB, where RRR, GGG, and BBB are integers ranging from 0 to 255. So, for example, lime green would be 000255000.

I need a function that can translate that into HTML-compatable hexidecimal colors. So, using the previous example, 000255000 would translate into #00FF00.

Can anyone do this for me?

Thanks in advance,
~takua108


----------



## DumberDrummer (Oct 27, 2003)

The dechex() function should be what you are looking for. 

Don't put the whole thing in there though, or it will convert it to a hex value that makes no sense, you have to do it by threes (255 is FF, 216 is D8, etc...)

My actual php skills are a little rusty however, so I won't try to write any code tonight, but if you are not up to the task, feel free to ask for my help.

EDIT: Also, if you put in values like 001, it will return only 1 with no zeros. Make sure to account for that in your code.


----------



## takua108 (Jan 4, 2006)

Thanks! Here's the code I wrote in the end:

```
function rgb2hex($r,$g,$b)
	{
	return strtoupper("#".str_pad(dechex($r),2,"0",STR_PAD_LEFT).str_pad(dechex($g),2,"0",STR_PAD_LEFT).str_pad(dechex($b),2,"0",STR_PAD_LEFT));
	}
```
And then to parse, for example, 255255255 into three seperate variables, you simply use substr. Here's how I did it:

```
$bodyr=substr($bodycolor,0,3);
$bodyg=substr($bodycolor,3,3);
$bodyb=substr($bodycolor,6,3);
$bodyhex=rgb2hex($bodyr,$bodyg,$bodyb);
```
You can see it in action if you wish:
1.) Go here.
2.) Click "Global Stats" on the sidebar
3.) Click on anyone's name
4.) Scroll down the list of statistics to see how well it works!


----------



## DumberDrummer (Oct 27, 2003)

sweet, glad I could help. I tried to write some code, but I couldn't figure out what to do about the fact that dechex only returns 1 if you put in 001, and you obviously fixed that!


----------

