How to convert hexadecimal color value to RGB value in php

Most of the CMS provides a color picker in admin panel to user to choose a color. And almost all of the color pickers return the color code as hexadecimal mode, e.g. #4EE4D3. So, you can just get the value and set the color in css. For example:



This is a very good practice. Problem occurs if you want to put a opacity option to the user. You can set background opacity with hexadecimal color value. You must use RGBA filter, so RGB color mode as well. Like:
background: rgba(233, 122, 234, 0.7);

So, we need to convert the hexadecimal value to its equivalent rgb value. Here is a very small function that will do the job:

You may also read:  header() function in the middle of a php page
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

view raw


hosted with ❤ by GitHub

So using this function you will get the rgb value, and with that you use the opacity :)

Hope you will enjoy! :)

You may also like...

Leave a Reply

%d bloggers like this: