PHP Function To Convert Hex To RGB

If you are working on a web app that does things with colours then you could find it useful to have function to convert between different colour types.

Here is a PHP snippet which allows you to convert HEX colours to RGB colours.

All you have to do is pass in the HEX colour as a parameter and it will return the RGB values as an array.

Improved Version

Here is an improved version of the above function to convert Hex to RGB thanks to Michael Kaiser. This function allows you to send in 6, 3, 2 or 1 digit Hex colours to the function and will still convert it to RGB.

if(strlen($match[1]) == 6) {
list($r, $g, $b) = array($hex[0].$hex[1],$hex[2].$hex[3],$hex[4].$hex[5]);
elseif(strlen($match[1]) == 3) {
list($r, $g, $b) = array($hex[0].$hex[0],$hex[1].$hex[1],$hex[2].$hex[2]);
else if(strlen($match[1]) == 2) {
list($r, $g, $b) = array($hex[0].$hex[1],$hex[0].$hex[1],$hex[0].$hex[1]);
else if(strlen($match[1]) == 1) {
list($r, $g, $b) = array($hex.$hex,$hex.$hex,$hex.$hex);
else {
return false;
$color = array();
$color[‘r’] = hexdec($r);
$color[‘g’] = hexdec($g);
$color[‘b’] = hexdec($b);
return $color;


Leave a reply