Generating a random hex color code with PHP

后端 未结 13 2239
半阙折子戏
半阙折子戏 2020-11-28 04:21

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?

相关标签:
13条回答
  • 2020-11-28 04:54

    This is how i do it.

    <?php echo 'rgba('.rand(0,255).', '.rand(0,255).', '.rand(0,255).', 0.73)'; ?>
    
    0 讨论(0)
  • 2020-11-28 04:59

    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.

    0 讨论(0)
  • 2020-11-28 04:59
    function random_color(){  
     return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
    }
    
    0 讨论(0)
  • 2020-11-28 05:03

    Shortest way:

    echo substr(uniqid(),-6); // result: 5ebf06
    
    0 讨论(0)
  • 2020-11-28 05:07

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

    $color= substr(str_shuffle('AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899'), 0, 6);
    
    0 讨论(0)
  • 2020-11-28 05:11

    If someone wants to generate light colors

    sprintf('#%06X', mt_rand(0xFF9999, 0xFFFF00));
    
    0 讨论(0)
提交回复
热议问题