Valid hexadecimal colors can contain from 0 to 9 and from A to F, so if we create a line with these characters and then mix it, we can get the first 6 characters to create a random hex color code. An example below!
the code
echo '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6);
I checked this in a while loop and generated 10,000 unique colors.
The 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 a result.
outis pointed out that my first example cannot generate hexadecimal numbers such as '4488CC', so I created a function that could generate hexadecimal numbers like this.
the 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 much more results than the first, but if you are not going to generate many color codes, then the first example will work just fine.
Jake Aug 12 '15 at 8:39 2015-08-12 08:39
source share