PHP code to generate color code

How to show color code using php?

The color code can be displayed using  hex or RGB format.

PHP str_shuffle() function is used to shuffle all the characters of a string randomly.

We have used string 'ABCDEF0123456789' in str_shuffle() function as argument to get 6 digit hex code combination of number and alphabates.

PHP substr() function is used to get 6 digit hex code from shuffled string.

Now this 6 digit hexadecimal code is followed by hash ( # ) which is used to generate color code.

We can use this hex color code to display color , background color in web pages.

We can convert hex color code to rgb code using below php code.

list($r, $g, $b) = sscanf($hexcode, "#%02x%02x%02x");

PHP Code to generate color code :

$color = substr(str_shuffle('ABCDEF0123456789'), 0, 6);

$hex_colorcode ='#' . $color; //Generate color code in 6 digit hex format.

list($r, $g, $b) = sscanf($hexcode, "#%02x%02x%02x");
$rgb_colorcode = "rgb($r, $g, $b)"; //Generate color code in RGB format.

Also you can use below php function to generate hexadecimals color code.

<?php

 function hexColorcode() {
   $str= 'ABCDEF0123456789';
   $color_code = '#';
   for ( $i = 0; $i < 6; $i++ ) {
      $color_code .= $str[rand(0, strlen($str) - 1)];
   }
   return $color_code;
}

echo hexColorcode();

?> 

Let's see below example to understand how to show color code using php progrram?

 

Example :

<div style="width:95%;">
<h3>PHP program to show list of HTML Color Codes</h3>
<p><h3>Pick Color with HEX and RGB code </h3></p>
<table width="100%" border="0" cellspacing="1" cellpadding="1">
<tr>
<td width="33%"><strong>Color</strong></td>
<td width="30%"><strong>Hex Code</strong></td>
<td width="30%"><strong>RGB Code</strong></td>
</tr>

<?
$colors = array();
while (true) {
$color = substr(str_shuffle('ABCDEF0123456789'), 0, 6);
$colors[$color] = '#' . $color;
if (count($colors) == 100 ) {

foreach($colors as $key=>$hexcode){
list($r, $g, $b) = sscanf($hexcode, "#%02x%02x%02x");

?>
<tr>
<td height='25' bgcolor='<?=$hexcode; ?>'></td>
<td><?=$hexcode; ?></td>
<td>rgb(<?=$r?>, <?=$g?>, <?=$b?>)</td>
</tr>
<?
}
break;
}
}

?>

</table>

</div>

Output :

Comments

Leave a Reply

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

22024