DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Random Color Generator

07.30.2011
| 4629 views |
  • submit to reddit
        Simple random color generator

<?php
function randomColor() {
    $str = '#';
    for($i = 0 ; $i < 6 ; $i++) {
        $randNum = rand(0 , 15);
        switch ($randNum) {
            case 10: $randNum = 'A'; break;
            case 11: $randNum = 'B'; break;
            case 12: $randNum = 'C'; break;
            case 13: $randNum = 'D'; break;
            case 14: $randNum = 'E'; break;
            case 15: $randNum = 'F'; break;
        }
        $str .= $randNum;
    }
    return $str;
}
$color = randomColor();
echo '<span style="color:'.$color.'">Random color: '.$color.'</span>';
?>
    

Comments

Snippets Manager replied on Sat, 2012/01/21 - 5:49pm

<?php $color = substr(md5(time()), 0, 6); ?>