Skip to main content
Added leading zeros for generated values shorter than 6 symbols. strtoupper example ommited because it's straightforward.
Source Link
$rand = str_pad(dechex(rand(0x000000, 0xFFFFFF)), 6, 0, STR_PAD_LEFT); echo('#' . $rand); 

You can change randrand() in for mt_randmt_rand() if you want, and you can put strtoupper()strtoupper() around the dechexstr_pad() to make the random number look nicer (although it’s not required). That would look like $rand = strtoupper(dechex(rand(0x000000, 0xFFFFFF)));

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

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

You can change rand in for mt_rand if you want, and you can put strtoupper() around the dechex to make the random number look nicer (although it’s not required). That would look like $rand = strtoupper(dechex(rand(0x000000, 0xFFFFFF)));

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

$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 :)

Source Link
Cas Bloem
  • 5.1k
  • 2
  • 26
  • 23

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

You can change rand in for mt_rand if you want, and you can put strtoupper() around the dechex to make the random number look nicer (although it’s not required). That would look like $rand = strtoupper(dechex(rand(0x000000, 0xFFFFFF)));

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