Convert Hex color to RGB with php

Converting hexadecimal colors to its RGB equivalent is not a big task with php built in function hexdec(). The hexdec() function returns decimal value of a hexadecimal number.

Here is a little custom function to achieve this. It takes one parameter, the hexadecimal color and returns an array of RGB color.
  
  function hexToRgb($hex){   
    $hex = ltrim($hex, '#');
    $chr = strlen($hex) / 3;
    if ($chr == 1 || $chr == 2) {
        list($r, $g, $b) = str_split($hex, $chr);
        return array(
            'r' => hexdec($r),
            'g' => hexdec($g),
            'b' => hexdec($b)
        );
   } else {
       return false;
     }
  }


Call function like this

$c = "#ff23a9";
print_r(hexToRgb($c))

This will output

Array ( [r] => 255 [g] => 35 [b] => 169 ) 

Convert Hex color to RGB with php Convert Hex color to RGB with php Reviewed by Altaf Hussain on 12:32 AM Rating: 5

No comments:

Altaf Web. Powered by Blogger.