php – How to create hex colors randomly?

Question:

How can I create hex color code randomly with PHP?

For example, from #000000 to #FFFFFF , to generate something like this:

<div style="color: <?= rand_color()?>">
     Estou colorido!
</div>

Answer:

An alternative way to accomplish this task, is to create an array containing the valid values ​​to create a color in hexadecimal the range is: 0-9A-F, this is done with range() which creates two arrays, one from 0 to 9 and another from A to F, array_merge() combines them.

Finally, a simple while checks if the string already has 7 characters (a pound followed by six alphanumers), otherwise, it generates a random number between 0 and 15 that is used as an index in $hex that has valid values.

<?php
$hex = array_merge(range(0, 9), range('A', 'F'));

$cor = '#';
while(strlen($cor) < 7){
    $num = rand(0, 15);
    $cor .= $hex[$num];
}

echo $cor;
Scroll to Top