How to generate random hex color in PHP

2 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

Related questions

...