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.

About Craig Lotter

Software developer, husband and dad to two young ladies. Writer behind An Exploring South African. I don't have time for myself any more.