Convert Hex to RGB in PHP

We are going to convert Hex to RGB in PHP.

We will create a function named hex2rgb that will convert the Hex to RGB or RGBa Values.

 

<?php 
function hex2rgb($hex,$alpha=false){
 list($r, $g, $b) = (strlen($hex) === 4) ? sscanf($hex, "#%1x%1x%1x") : sscanf($hex, "#%2x%2x%2x");
 $rgb = array('r'=>$r,'g'=>$g,'b'=>$b);
	if($alpha){
		$rgb['a'] = $alpha;
	}
	return $rgb;
}
?>

Now, When you Call the hex2rgb function passing the Hex Value, it will return an array containing RGB value.

For Example:

<?php

  hex2rgb("#f2f"); //Return Array ( [r] => 15 [g] => 2 [b] => 15 )

  hex2rgb("#2d2d2d"); //Return Array ( [r] => 45 [g] => 45 [b] => 45 )

  hex2rgb("#3d3d3d",0.45);  //Return Array ( [r] => 61 [g] => 61 [b] => 61 [a] => 0.45 )

?>

If you like the Code, Please don’t forget to share it with your friends.

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

4 Responses

  1. piyush says:

    Thanks for posting this code.

  2. Md.Arman says:

    Great post .
    Hope you have a great ahead regrd .

Leave a Reply

Your email address will not be published. Required fields are marked *

shares