Get Random Color using PHP

Returning random colors is quite simple. You just need to create a PHP variable that returns a color. We will look into two different methods to get random color using PHP; in HEX and in RGB.

See it in Action?

Random HEX Color in PHP

Just create a variable that uses the rand method with a range that starts from black 0x000000 and ends with white 0xFFFFFF. We will then wrap the whole thing with a dechex method which converts a decimals into hexadecimals. Finally, echo out that variable wherever you need it.

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

Random RGB Color in PHP

Just create a variable that uses the rand method with a range that starts from 0 and ends with 255. And now, just echo out that variable.

$color = 'rgb(' . rand(0,255) . ',' . rand(0,255) . ',' . rand(0, 255) . ')';
echo $color;

This is also possible in JS. See JavaScript version

Post a Comment

To post code, use the code tag with a class language-*
Examples: code class="language-markup"code class="language-css"