How to convert Hex Color to RGB with PHP

Sometimes we need to convert HEX values of the colors in RGB values. I also faced this problem when I need to transfer HTML color picker value to PHP fpdf. There are many other use of RGB colors in various area of web designing. This problem is not big problem. There are various online tools available to convert Hex colors to RGB. If you want to create a PHP code for this, you can try the code added in the post below.
See the function hex2rgb()
function hex2rgb($hex) { $hex = str_replace("#", "", $hex); if(strlen($hex) == 3) { $r = hexdec(substr($hex,0,1).substr($hex,0,1)); $g = hexdec(substr($hex,1,1).substr($hex,1,1)); $b = hexdec(substr($hex,2,1).substr($hex,2,1)); } else { $r = hexdec(substr($hex,0,2)); $g = hexdec(substr($hex,2,2)); $b = hexdec(substr($hex,4,2)); } $rgb = array($r, $g, $b); //return implode(",", $rgb); // returns the rgb values separated by commas return $rgb; // returns an array with the rgb values }
This function works with both shorthand hex codes such as #f00 and longhand hex codes such as #ff0000. It also accepts the number sign (#) just in case.
You can use this function as given below
$rgb = hex2rgb("#cc0"); print_r($rgb);
Above lines will print the rgb values of the hex passed to the function. Now you can use this function to get the RGB values of the hex.
Enjoy this coding.
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.