How to convert from HEX color to RGB in PHP

2 Answers

0 votes
function hex2rgb($hex) {
   $hex = str_replace("#", "", $hex);
 
   if (strlen($hex) == 3) {
        $ch = substr($hex, 0, 1);
        $r = hexdec($ch.$ch);
        $ch = substr($hex, 1, 1);
        $g = hexdec($ch.$ch);
        $ch = substr($hex, 2, 1);
        $b = hexdec($ch.$ch);
   } 
   else {
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
   }
   
   return array($r, $g, $b);
}
 
$rgb = hex2rgb("#ff0");
echo $rgb[0].','.$rgb[1].','.$rgb[2] . "\n";

$rgb = hex2rgb("#f0f");
print_r($rgb);
 
$rgb = hex2rgb("#ffff0");
echo $rgb[0].','.$rgb[1].','.$rgb[2] . "\n";

$rgb = hex2rgb("#fa9805");
echo $rgb[0].','.$rgb[1].','.$rgb[2] . "\n";

 
 
/*
run:
 
255,255,0
Array
(
    [0] => 255
    [1] => 0
    [2] => 255
)
255,255,0
250,152,5
 
*/

 



answered Sep 3, 2015 by avibootz
edited Mar 6, 2025 by avibootz
0 votes
function hexToRgb($hex) {
    // Remove the '#' if it exists
    $hex = ltrim($hex, '#');

    // Expand shorthand hex codes (e.g., #ff0 to #ffff00)
    if (strlen($hex) == 3) {
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    }

    // Parse the hex code
    list($r, $g, $b) = sscanf($hex, "%02x%02x%02x");

    return array($r, $g, $b);
}

$hex1 = "#ff0";
list($r1, $g1, $b1) = hexToRgb($hex1);
echo $r1 . ',' . $g1 . ',' . $b1 . "\n";

$hex2 = "#f0f";
list($r2, $g2, $b2) = hexToRgb($hex2);
echo $r2 . ',' . $g2 . ',' . $b2 . "\n";

$hex2 = "#ffff0";
list($r2, $g2, $b2) = hexToRgb($hex2);
echo $r2 . ',' . $g2 . ',' . $b2 . "\n";

$hex2 = "#fa9805";
list($r2, $g2, $b2) = hexToRgb($hex2);
echo $r2 . ',' . $g2 . ',' . $b2 . "\n";

$hex3 = "fa9805"; //test without #
list($r3, $g3, $b3) = hexToRgb($hex3);
echo $r3 . ',' . $g3 . ',' . $b3 . "\n";

 
 
/*
run:
 
255,255,0
255,0,255
255,255,0
250,152,5
250,152,5
 
*/

 



answered Mar 6, 2025 by avibootz

Related questions

1 answer 226 views
2 answers 248 views
2 answers 217 views
2 answers 248 views
2 answers 229 views
229 views asked Mar 6, 2025 by avibootz
2 answers 241 views
1 answer 164 views
164 views asked Mar 6, 2025 by avibootz
...