/*
Generate unique HEX colors using randomness in PHP.
Notes:
- random_int() provides strong randomness and different results each run.
- Uniqueness ensured using an associative array as a set.
- Produces #RRGGBB strings.
*/
// Convert an integer (0–255) to a two-digit HEX string.
function toHex(int $value): string {
return strtolower(str_pad(dechex($value), 2, '0', STR_PAD_LEFT));
}
// Generate N unique random HEX colors.
function generateRandomUniqueHexColors(int $count): array {
$seen = [];
$colors = [];
while (count($colors) < $count) {
$r = random_int(0, 255);
$g = random_int(0, 255);
$b = random_int(0, 255);
$hex = "#" . toHex($r) . toHex($g) . toHex($b);
if (!isset($seen[$hex])) {
$seen[$hex] = true;
$colors[] = $hex;
}
}
return $colors;
}
// Example usage
$n = 12;
$colors = generateRandomUniqueHexColors($n);
echo "Generated HEX colors:\n";
foreach ($colors as $c) {
echo $c . "\n";
}
/*
run:
Generated HEX colors:
#985846
#304408
#d8cbbb
#7103ea
#2b42da
#5b88fa
#1bbd09
#d3bbb0
#85642a
#cee76e
#fb7392
#dc0952
*/