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.


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

Mathi said...

The gave data's are extremely valuable to me. It's a superb website for learning web application. Much obliged to you for sharing this brilliant blog.
PHP Course Chennai | PHP course | PHP courses in Chennai | PHP Training in Chennai

ProPlus Academy said...

Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
digital marketing course in coimbatore
php training in coimbatore