Convert Hex Color to RGB using PHP
by c.bavota | Posted in Tutorials | 10 comments
Converting certain values back and forth is often necessary when developing functions to help your website work the way you want it to. I needed a function that would convert a hex color to rgb and for some reason it took me a while to figure it out.
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
}
This function works with both shorthand hex codes such as #f00 and longhand hex codes such as #ff0000. It also accepts the number sign (#) just in case. You can see there are two return lines at the end of the function. The first, which is commented out, will return the rgb values separated by a comma. The second, which is the default, will return an array with the rgb values.
So now with this function in place we can use it like so:
$rgb = hex2rgb("#cc0");
print_r($rgb);
The above function would output:
Array ( [0] => 204 [1] => 204 [2] => 0 )
Since we are going one way with this, might as well go the other. Here is a function to convert rgb to a hex color:
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 (#)
}
This function works like so:
$rgb = array( 255, 255, 255 ); $hex = rgb2hex($rgb); echo $hex;
The above function would output:
#ffffff



Thanks for the rgb convert help. I would have never figured it out.
That’s a neat little script – so glad I found this site – it’s just what I needed!
Bavotasan, this is great. We’re always looking for a way to deliver consistent results across all platforms, this is another tool for the arsenal!
Great coding! Thanks for sharing this RGB converter
I was looking for something like that. This will save me a lot of time, thanks!
I have always looked for something like this to help me convert HEX colors from RGB. Thanks bavota, I have used this a couple of months ago and I can surely say that it is very helpful!
I am just writing this comment because I love your post main image so much. Feels like a music system is on
really attractive.
Maybe I notice such creative things pretty quickly because I am attracted to design and share design inspirations as well at my blog.
Thanks for sharing this RGB converter
Thank you so much!
I adjusted this script on my page to suit my needs, hope you don’t mind
God bless
I would have never figured it out.