Generating a random hex color code with PHP

后端 未结 13 2312
半阙折子戏
半阙折子戏 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));
    }
    

提交回复
热议问题