Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,003 questions

51,950 answers

573 users

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 50 views
1 answer 103 views
2 answers 101 views
2 answers 71 views
2 answers 80 views
2 answers 84 views
2 answers 97 views
...