joshdcomp
joshdcomp

Reputation: 1678

Generating a random hex color code with PHP

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?

Upvotes: 101

Views: 176578

Answers (17)

Abhishek
Abhishek

Reputation: 93

you can use

function getRandomColor()
    {
        $letters = '0123456789ABCDEF';
        $color = '#';
        for ($i = 0; $i < 6; $i++) {
            $color .= $letters[rand(0, 15)];
        }
        return $color;
    }

Upvotes: 0

mondayrris
mondayrris

Reputation: 724

I have noticed a comment and hereby post an answer. The old concept of Web safe colours is great. I want to remember it.

First, create inc/Palette.php

<?php

class Palette
{
    private static $items = [];

    /**
     * Direct text from https://en.wikipedia.org/wiki/Web_colors#Web-safe_colors
     * Copy and paste, then replace any odd space blocks with a normal space
     *
     * @return string
     */
    private static function raw()
    {
        return "*000* 300 600 900 C00 *F00*
*003* 303 603 903 C03 *F03*
006 306 606 906 C06 F06
009 309 609 909 C09 F09
00C 30C 60C 90C C0C F0C
*00F* 30F 60F 90F C0F *F0F*
030 330 630 930 C30 F30
033 333 633 933 C33 F33
036 336 636 936 C36 F36
039 339 639 939 C39 F39
03C 33C 63C 93C C3C F3C
03F 33F 63F 93F C3F F3F
060 360 660 960 C60 F60
063 363 663 963 C63 F63
066 366 666 966 C66 F66
069 369 669 969 C69 F69
06C 36C 66C 96C C6C F6C
06F 36F 66F 96F C6F F6F
090 390 690 990 C90 F90
093 393 693 993 C93 F93
096 396 696 996 C96 F96
099 399 699 999 C99 F99
09C 39C 69C 99C C9C F9C
09F 39F 69F 99F C9F F9F
0C0 3C0 6C0 9C0 CC0 FC0
0C3 3C3 6C3 9C3 CC3 FC3
0C6 3C6 6C6 9C6 CC6 FC6
0C9 3C9 6C9 9C9 CC9 FC9
0CC 3CC 6CC 9CC CCC FCC
0CF 3CF 6CF 9CF CCF FCF
*0F0* 3F0 *6F0* 9F0 CF0 *FF0*
0F3 *3F3* *6F3* 9F3 CF3 *FF3*
*0F6* *3F6* 6F6 9F6 *CF6* *FF6*
0F9 3F9 6F9 9F9 CF9 FF9
*0FC* *3FC* 6FC 9FC CFC FFC
*0FF* *3FF* *6FF* 9FF CFF *FFF*";
    }

    public static function webSafeColors() {
        if (empty(self::$items)) {
            self::$items = explode(' ', str_replace(['*', "\n"], ['', ' '], self::raw()));
        }
        return self::$items;
    }

    public static function randomColor() {
        $colors = self::webSafeColors();
        $count = count($colors);

        return '#' . $colors[rand(0, $count - 1)];
    }
}

In somewhere include this file like:

include __DIR__ . '/../inc/Palette.php';

// dump the result
var_dump(Palette::randomColor());

Upvotes: 0

DEV Tiago Fran&#231;a
DEV Tiago Fran&#231;a

Reputation: 1706

function randomRGB()
{
    $r = rand(0, 255);
    $g = rand(0, 255);
    $b = rand(0, 255);

    return "rgb({$r}, {$g}, {$b})";
}

function randomHexColor()
{
    return '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6);
}

$hexColor = randomHexColor();
$rgbColor = randomRGB();

Upvotes: 1

TURTLE
TURTLE

Reputation: 3847

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.

Upvotes: 21

garrettlynchirl
garrettlynchirl

Reputation: 910

This is heavily based on the @Galen version above, however, I wanted to add range control that could limit the colour produced to be red, green, blue, lighter or darker. It might be of use to others.

function random_colour_part($lower, $upper)
{
    //randomly select colour in range and convert to hexidecimal
    return str_pad(dechex(mt_rand($lower, $upper)), 2, '0', STR_PAD_LEFT);
}

function random_colour($colour)
{
    //loop through colour
    foreach ($colour as $key => $value)
    {
        //retrieve each r,g,b colour range and generate random hexidecimal colour
        if ($key == "r") $r = random_colour_part($value[0], $value[1]);
        if ($key == "g") $g = random_colour_part($value[0], $value[1]);
        if ($key == "b") $b = random_colour_part($value[0], $value[1]);
    }

    //return hexidecimal colour
    return "#" . $r . $g . $b;
}

//generate a random red-based colour
echo random_colour(["r"=>[0,255], "g"=>[0,0], "b"=>[0,0]]);

//generate a random light green-based colour (use only half of the 255 range)
echo random_colour(["r"=>[0,0], "g"=>[127,255], "b"=>[0,0]]);

//generate a random colour of any sort
echo random_colour(["r"=>[0,255], "g"=>[0,255], "b"=>[0,255]]);

Upvotes: 3

MudithaE
MudithaE

Reputation: 617

If someone wants to generate light colors

sprintf('#%06X', mt_rand(0xFF9999, 0xFFFF00));

Upvotes: 9

Cas Bloem
Cas Bloem

Reputation: 5050

$rand = str_pad(dechex(rand(0x000000, 0xFFFFFF)), 6, 0, STR_PAD_LEFT);
echo('#' . $rand);

You can change rand() in for mt_rand() if you want, and you can put strtoupper() around the str_pad() to make the random number look nicer (although it’s not required).

It works perfectly and is way simpler than all the other methods described here :)

Upvotes: 43

Shaz
Shaz

Reputation: 425

function random_color(){  
 return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}

Upvotes: 4

Jeff Janes
Jeff Janes

Reputation: 895

I think this would be good as well it gets any color available

$color= substr(str_shuffle('AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899'), 0, 6);

Upvotes: 1

Jeeva
Jeeva

Reputation: 642

This is how i do it.

<?php echo 'rgba('.rand(0,255).', '.rand(0,255).', '.rand(0,255).', 0.73)'; ?>

Upvotes: 6

Cyril
Cyril

Reputation: 3148

Shortest way:

echo substr(uniqid(),-6); // result: 5ebf06

Upvotes: 8

ceejayoz
ceejayoz

Reputation: 180023

Web-safe colors are no longer necessary (nor a valid concept, even) as even mobile devices have 16+ bit colour these days.

See Wikipedia for more info.

In other words, use any colour from #000000 to #FFFFFF.

edit: Dear downvoters. Check the edit history for the question first.

Upvotes: 3

Cas Bloem
Cas Bloem

Reputation: 5050

$color = sprintf("#%06x",rand(0,16777215));

Upvotes: 17

danorton
danorton

Reputation: 12015

As of PHP 5.3, you can use openssl_random_pseudo_bytes():

$hex_string = bin2hex(openssl_random_pseudo_bytes(3));

Upvotes: 4

Susheel
Susheel

Reputation: 1679

you can use md5 for that purpose,very short

$color = substr(md5(rand()), 0, 6);

Upvotes: 57

Galen
Galen

Reputation: 30170

Get a random number from 0 to 255, then convert it to hex:

function random_color_part() {
    return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}

function random_color() {
    return random_color_part() . random_color_part() . random_color_part();
}

echo random_color();

Upvotes: 110

outis
outis

Reputation: 77410

An RGB hex string is just a number from 0x0 through 0xFFFFFF, so simply generate a number in that range and convert it to hexadecimal:

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

or:

function rand_color() {
    return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}

Upvotes: 188

Related Questions