Sunday, July 26, 2009

PHP: Generate random color code

Hello! today I was surfing the net again reading up articles when I came across this website which has a few codes on several uses. but their snippets were quite full of flaws and vulnerability.

well, I am going to talk about one of their code snippets: - Generating random color code.

Here's mine, a function that generates CSS-compatible colour code in hexadecimal:

function rand_colorCode(){
$r = dechex(mt_rand(0,255)); // generate the red component
$g = dechex(mt_rand(0,255)); // generate the green component
$b = dechex(mt_rand(0,255)); // generate the blue component
$rgb = $r.$g.$b;
if($r == $g && $g == $b){
$rgb = substr($rgb,0,3); // shorter version
return '#'.$rgb;

$code = rand_colorCode();
echo 'This code is '.$code.'';


Isn't this much better than the one posted at Note that this function doesn't utilize the functions in GD, but you can use the RGB in GD.

1 comment:

Sankar lp said...

I have read your blog its very attractive and impressive. I like it your blog.

PHP 7 Training in chennai | PHP 7 Training Course

PHP 7 Training in chennai | Online PHP 7 Course