PHP: Convert Web Hex Color Code to RGB Array Programming 18 OCT 2010

green php elephants - elephpantsSometimes you need to RGB array that makes up a color when working in the wonderful world of PHP. Don’t ask me why or when, though that said, I have required it at least once before when setting text color whilst generating PDFs using the FPDF library – so I have at least established that you do sometimes want to do this.

So let’s scribble down a neat little function that will convert a plain old web hex color to its RGB components for us then, shall we?

function convertHexToRGB($hex) {
    $hex = ereg_replace("#", "", $hex);
    $color = array();
    if(strlen($hex) == 3) {
            $color['r'] = hexdec(substr($hex, 0, 1));
            $color['g'] = hexdec(substr($hex, 1, 1));
            $color['b'] = hexdec(substr($hex, 2, 1));
    else if(strlen($hex) == 6) {
            $color['r'] = hexdec(substr($hex, 0, 2));
            $color['g'] = hexdec(substr($hex, 2, 2));
            $color['b'] = hexdec(substr($hex, 4, 2));
    return $color;

As you can see, the function does little more than make use of the useful hexdec function, though it neatly deals with hex codes that may or may not come in with the standard # prefix, or in the shorthand three character length instead of the standard six characters.

So now you know.

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Bálint Kléri

    Thank you for this quick tip, it was useful for me.
    But you shouldn’t use ereg_replace, because it has been deprecated in PHP 5.3.0. Use preg_replace() instead.
    And I don’t understand, what is for the $r, $b and $g variables in the first if.

    • actually now that I look at it, I think that might be a copy & paste error! Those three undeclared variables should definitely not be in there!