Tuesday 26 July 2016

HEX to RGB convertor in PHP

PHP function to convert HEX code to RGB values. This functions takes HEX code as input and returns rgb values. It can be customized to return a string of rgb values separated by comma or can be set to return rgb values as an array.

function hexToRGB($hex_code) {
    $hex_code = str_replace("#", "", $hex_code);
   
    if(strlen($hex_code) == 3) {
        $red = hexdec(substr($hex_code,0,1).substr($hex_code,0,1));
        $green = hexdec(substr($hex_code,1,1).substr($hex_code,1,1));
        $blue = hexdec(substr($hex_code,2,1).substr($hex_code,2,1));
    } else {
        $red = hexdec(substr($hex_code,0,2));
        $green = hexdec(substr($hex_code,2,2));
        $blue = hexdec(substr($hex_code,4,2));
    }
    $rgb = array($red, $green, $blue);
    //return implode(",", $rgb); // rgb values will be returned as string separated by commas
    return $rgb; // rgb values will be returned as an array
}

No comments:

Post a Comment