Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a series of unique HEX colors in PHP

2 Answers

0 votes
/*
    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

*/

 



answered 17 hours ago by avibootz
0 votes
/**
 * Generate N unique random HEX colors (#RRGGBB).
 */
function generateRandomUniqueHexColors(int $count): array
{
    $colors = [];

    while (count($colors) < $count) {
        $hex = sprintf(
            '#%02x%02x%02x',
            random_int(0, 255),
            random_int(0, 255),
            random_int(0, 255)
        );

        $colors[$hex] = true; // associative array as a set
    }

    return array_keys($colors);
}

// Example usage
$colors = generateRandomUniqueHexColors(12);

echo "Generated HEX colors:\n";
foreach ($colors as $c) {
    echo $c . "\n";
}


/*
run:

Generated HEX colors:
#7ff8fe
#70ece5
#39664c
#6e15e7
#8db926
#318f43
#0302fe
#473d37
#70bae5
#3945b4
#45a62e
#716605

*/

 



answered 15 hours ago by avibootz
...