Convert Hex to Decimal Functions

Colors in HTML and CSS are almost always rendered using hexadecimal values. But, often imaging software uses RGB values instead. There are a million converters out there (including our own Hexadecimal Color Generator) that you can use online, but if you have lots of conversions to make, that can get tiresome. So, here are the PHP functions you need to do it yourself.

If you want to convert the hexadecimal (sometimes called hexdec) value back the decimal Red Green Blue values, this is the function you'll want to use:

function convertHexdec($hexdec) {
    if (substr($hexdec,0,1) == '#') { $hexdec = substr($hexdec,1); }
    if (strlen($hexdec) != 6) { die('Error! For this function, the hexadecmical value needs to be 6 characters in length.'); }
    $redhex = substr($hexdec,0,2);
    $greenhex = substr($hexdec,2,2);
    $bluehex = substr($hexdec,4,2);
    $red = round(hexdec($redhex));
    $green = round(hexdec($greenhex));
    $blue = round(hexdec($bluehex));
    $hexdec = strtoupper($hexdec);
    return array('hexdec'=>$hexdec,'red'=>$red,'green'=>$green,'blue'=>$blue);

And if you already have the RGB values and want to get the hexadecimal value, you'll want to use this one instead:

function convertRGB($red,$green,$blue) {
    $colors = array('red','green','blue');
    $hexdec = '';
    foreach ($colors as $color) {
        $color = round($$color);
        if ($color > 255) { $color = 255; }
        if ($color < 0) { $color = 0; }
        ${$color.'hex'} = dechex($color);
        if (strlen(${$color.'hex'}) < 2) { ${$color.'hex'} = '0'.${$color.'hex'}; }
        $hexdec .= ${$color.'hex'};
    $hexdec = strtoupper($hexdec);
    return array('hexdec'=>$hexdec,'red'=>$red,'green'=>$green,'blue'=>$blue);



This post was published on November 23rd, 2010 by Robert James Reese in the following categories: CSS, HTML, and PHP Before using any of the code or other content in this post, you must read and agree to our terms of use.