How to create hexadecimal colors randomly

1

How can I create color code in hexadecimal randomly with PHP?

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

<div style="color: <?= rand_color()?>">
     Estou colorido!
</div>
    
asked by anonymous 11.12.2015 / 14:23

2 answers

1

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 () makes a combination of them.

Finally a simple while checks whether the string already has 7 characters (one followed by six alphanumeric characters), otherwise it generates a random number between 0 and 15 that is used as an index in% with_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;
    
11.12.2015 / 14:51
1

In php you can do this quite simply:

sprintf('#%06X', mt_rand(0, 0XFFFFFF));

Explaining:

# is the initial character used for color in hexadecimal in HTML

%06 means random values will be filled with 0 up to 6 times if it does not reach 6 characters

The X of %06X is the formatting of sprintf that interprets a given value as hexadecimal . In this case we use the x uppercase to generate the letters of the hexadecimal in capital letters too.

mt_rand will be responsible for generating a random number from 0 to 16777215 . The 16777215 number comes from the hexadecimal expression 0xFFFFFF .

Note : Although I think this was very simple, I'm open to other answers with other methods.

    
11.12.2015 / 14:23