Tutorial Random Hex Color

by in , 0

Technique #1

<?php 
    
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    
?>

Then echo out the $color value anywhere you need it. For example:

<body style="background: <?php echo $color; ?>;">

Technique #2

<?php printf( "#%06X\n", mt_rand( 0, 0xFFFFFF )); ?>

There is also a JavaScript version.

Reference URL

Leave a Reply