PHP Convert Hex to RGB
![](https://www.thekaratecoder.com/wp-content/uploads/2020/06/hex-to-rgb.png)
Need a way to convert Hex code to RGB value programmatically with PHP? I got your back.
<?php
/**
* Converts a hex code to the rgb value
*
* @param hex hex code with or without the # symbol
* @return string
*/
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
}
?>
There are not a ton of instances that you might need to do this. Most of the cases I had to use this have been for better support for older browsers.