Skip to content

Instantly share code, notes, and snippets.

@harish81
Last active June 2, 2021 03:42
Show Gist options
  • Save harish81/01491dd3cba0738f61aeb1597f4247d1 to your computer and use it in GitHub Desktop.
Save harish81/01491dd3cba0738f61aeb1597f4247d1 to your computer and use it in GitHub Desktop.
PHP function to convert hex color to RGB with alpha support
/**
* Convert the hex color to rgba.
* @param $hex - #fa11cc
* @param mixed $alpha - from 0.0 to 1.0
* @return array rgba
*/
function hexToRgb($hex, $alpha = false)
{
$hex = str_replace('#', '', $hex);
$length = strlen($hex);
$rgb['red'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0)) / 255;
$rgb['green'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0)) / 255;
$rgb['blue'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0)) / 255;
if ($alpha) {
$rgb['alpha'] = $alpha;
}
return $rgb;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment