You can change rand() in for mt_rand() if you want, and you can put strtoupper() around the str_pad() to make the random number look nicer (although it’s not required).
It works perfectly and is way simpler than all the other methods described here :)
Valid hex colors can contain 0 to 9 and A to F so if we create a string with those characters and then shuffle it, we can grab the first 6 characters to create a random hex color code. An example is below!
outis pointed out that my first example couldn't generate hexadecimals such as '4488CC' so I created a function which would be able to generate hexadecimals like that.
The second example would be better to use because it can return a lot more different results than the first example, but if you aren't going to generate a lot of color codes then the first example would work just fine.
This is heavily based on the @Galen version above, however, I wanted to add range control that could limit the colour produced to be red, green, blue, lighter or darker. It might be of use to others.
function random_colour_part($lower, $upper)
{
//randomly select colour in range and convert to hexidecimal
return str_pad(dechex(mt_rand($lower, $upper)), 2, '0', STR_PAD_LEFT);
}
function random_colour($colour)
{
//loop through colour
foreach ($colour as $key => $value)
{
//retrieve each r,g,b colour range and generate random hexidecimal colour
if ($key == "r") $r = random_colour_part($value[0], $value[1]);
if ($key == "g") $g = random_colour_part($value[0], $value[1]);
if ($key == "b") $b = random_colour_part($value[0], $value[1]);
}
//return hexidecimal colour
return "#" . $r . $g . $b;
}
//generate a random red-based colour
echo random_colour(["r"=>[0,255], "g"=>[0,0], "b"=>[0,0]]);
//generate a random light green-based colour (use only half of the 255 range)
echo random_colour(["r"=>[0,0], "g"=>[127,255], "b"=>[0,0]]);
//generate a random colour of any sort
echo random_colour(["r"=>[0,255], "g"=>[0,255], "b"=>[0,255]]);