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 random color in HEX format with PHP

4 Answers

0 votes
function generateRandomHexColor() {
    return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}


$str = generateRandomHexColor();

echo $str;



 
 
/*
run:
 
#bfd13b

*/

 



answered Sep 30, 2021 by avibootz
0 votes
function generateRandomHexColor() {
     return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}


$str = generateRandomHexColor();

echo $str;



 
 
/*
run:
 
#43D9B1

*/

 



answered Sep 30, 2021 by avibootz
0 votes
function generateRandomHexColor(): string {
    $hexChars = '0123456789ABCDEF';
    $hex = '';
 
    for ($i = 0; $i < 6; $i++) {
        $hex .= $hexChars[rand(0, 15)];
    }
 
    return $hex;
}
 
$hexColor = generateRandomHexColor();
 
echo "Random HEX Color: #$hexColor\n";
 
 
 
/*
run:
 
Random HEX Color: #13C788
 
*/

 



answered 1 day ago by avibootz
0 votes
/**
 * Generate a random color in HEX format (#RRGGBB)
 * This program demonstrates how numbers and bits are used
 * to produce a valid 24‑bit color value.
 */

/**
 * Create a 24‑bit random integer (0x000000–0xFFFFFF).
 * random_int() provides cryptographically secure randomness.
 * 0x1000000 = 2^24, giving us exactly 24 bits of color data.
 */
function randomColorInt(): int {
    // 24 bits → values from 0 to 16,777,215 (0xFFFFFF)

    return random_int(0, 0xFFFFFF);
}

/**
 * Convert a 24‑bit integer into a hex color string.
 * sprintf("%06X") ensures exactly 6 uppercase hex digits.
 */
function intToHexColor(int $value): string {
    $hex = sprintf("%06X", $value); // Convert to 6‑digit hex

    return "#{$hex}";
}

/**
 * Produce a random hex color by combining the two functions.
 */
function generateRandomHexColor(): array {
    $value = randomColorInt();        // 24‑bit random number
    $hex   = intToHexColor($value);   // Convert to #RRGGBB

    return [
        'value' => $value,
        'hex'   => $hex
    ];
}

// Run the program
$result = generateRandomHexColor();

echo "Random 24‑bit value: {$result['value']}\n";
echo "Hex color: {$result['hex']}\n";


/*
run:

Random 24‑bit value: 14657487
Hex color: #DFA7CF

*/

 



answered 1 day ago by avibootz
...