I\'m working on a project where I need to generate an undefined number of random, hexadecimal color codes…how would I go about building such a function in PHP?
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!
code
echo '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6);
I tested this in a while loop and generated 10,000 unique colors.
code I used to generate 10,000 unique colors:
$colors = array();
while (true) {
$color = substr(str_shuffle('ABCDEF0123456789'), 0, 6);
$colors[$color] = '#' . $color;
if ( count($colors) == 10000 ) {
echo implode(PHP_EOL, $colors);
break;
}
}
Which gave me these random colors as the result.
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.
code
function randomHex() {
$chars = 'ABCDEF0123456789';
$color = '#';
for ( $i = 0; $i < 6; $i++ ) {
$color .= $chars[rand(0, strlen($chars) - 1)];
}
return $color;
}
echo randomHex();
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.