Generating a random hex color code with PHP

后端 未结 13 2237
半阙折子戏
半阙折子戏 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:48

    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));
    }
    
    0 讨论(0)
  • 2020-11-28 04:48

    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.

    0 讨论(0)
  • 2020-11-28 04:51
    $color = sprintf("#%06x",rand(0,16777215));
    
    0 讨论(0)
  • 2020-11-28 04:52
    $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 :)

    0 讨论(0)
  • 2020-11-28 04:53

    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();
    
    0 讨论(0)
  • 2020-11-28 04:54

    you can use md5 for that purpose,very short

    $color = substr(md5(rand()), 0, 6);
    
    0 讨论(0)
提交回复
热议问题