How to create hexadecimal colors randomly?

Asked

Viewed 696 times

6

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

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

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

4 answers

10


An alternative way to perform this task is to create an array containing valid values to create a hexadecimal color the range is: 0-9A-F, this is done with crease() which creates two arrays, one from 0 to 9 and the other from A to F, array_merge() makes combination of them.

Finally a simple while checks whether the string already has 7 characters (a sharp followed by six alphanumeric), otherwise it generates a random number between 0 and 15 that is used as an input in $hex which 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;

9

In php you can make it very simple:

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

Explaining:

# is the initial character used for hexadecimal colors in HTML

%06 means that the 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 which interprets a certain value as hexadecimal. We use in this case the x capital letters to generate hexadecimal in capital letters as well.

mt_rand will be in charge of generating a random number from 0 until 16777215. The number 16777215 is derived from the expression hexadecimal 0xFFFFFF.

Updating

Starting with PHP 7, PHP now has a function called random_int.

It is also possible to use it:

function random_color()
{
    return sprintf('#06x', random_int(0, 0xFFFFFF));
}
  • 5

    In view of the fact that random_int is cryptographically secure, can be a little slower than mt_rand. Moreover, as the goal is only to generate a color random, I leave the question: really worth it?

3

In the detail of the question is asked a solution in PHP, but usually PHP runs in web environments, starting from that pre-supposed you do not necessarily need to run it in PHP.

In certain cases we need to evaluate whether it is really worth giving the server the task of something so simple that it can run on the client side, such as giving color to something in the HTML interface.

Client-side processing is better because you don’t know if server-side features are free and it can easily handle requests. But sending large amounts of data to the client for processing will incur customer overload and make your browsing experience less acceptable, imagine ordering from the server for each color? The network may get overloaded and the bandwidth consumed. Server-side data processing will increase server load for each new client.

Therefore, to avoid these problems, it is best to first transfer some of these conflicts to the client side since color elements should not be security issues.

Also, I’m assuming that Javascript is enabled.

A solution with javascript would be to use random mathematical functions such as:

Math.floor(Math.random() * 16777215).toString(16);

Example of use

for(let i=0;i<=60;i++){
 document.write('<div data-randcolor>  Estou colorido!</div>');
}


let randHexColor = () => {
  return "#" + Math.floor(Math.random() * 16777215).toString(16);
}


window.addEventListener('load', function(){
  let randColor = document.querySelectorAll('[data-randcolor]');
  randColor.forEach((elm) => {
    elm.style.color = randHexColor();
   });
});

// Discoteca
setInterval(()=>{
  document.body.style.backgroundColor = randHexColor();
  let randColor = document.querySelectorAll('[data-randcolor]');
  randColor.forEach((elm) => {
    elm.style.color = randHexColor();
   });
},500);
body {
  margin: 0;
  height: 100vh;  
  font-family: Helvetica neue, roboto;
  background-color: #000;
}
div {
display:block;
width: 100%;
}

Orchestrating and running javascript with PHP

The question is about PHP and there are several ways that have already posted here and all are valid. I would like to introduce a somewhat known aspect that is the execution of javascript scripts V8 natively by PHP.

This case can be used for example to implement a Javascript micro-services orchestrated by a PHP engine that aggregates everything.

You can run javascript with PHP using extension V8js running a Javascript V8 engine natively in PHP to interpret it.

<?php

$v8 = new V8Js();

/* basic.js */
$JS = <<< EOT
let randHexColor = () => {
  return "#" + Math.floor(Math.random() * 16777215).toString(16);
} 
let len = print('Cor aleatória' + ' ' + randHexColor());
randHexColor();


EOT;

try {
  var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
  var_dump($e);
}

?>

Javascrip will be run by the interpreter and you can get the output of it, all V8 functions are available, which makes you extend php functionality to what may only be present in V8.

Alternative PHP

Of course, running a Javascript V8 engine might seem a bit of an exaggeration to just generate a random string and maybe you’re in an environment that runs nothing in the client like for example the command line or a REST API. The Approach is always the same, some mathematical function to generate the string and is just what the function mt_rand makes, generates random numbers, in this case hexadecimal random:

<?php 
printf( "#%06X\n", mt_rand( 0, 0xFFFFFF ));
?>
  • 1

    Congratulations on the answer! Server-side processing is silly (of course, according to the requirements of the question it asks for PHP) but without a doubt is the best answer.

  • 2

    I even understand the concern of running on the client-side so as not to spend server-side resources for nothing. This part of the response is great. But the part about using V8, I think it’s an exaggeration. I’d still be left with only the native PHP functions anyway.

  • @Wallacemaxters was just out of curiosity, since I was talking about javascript and php.

0

There are several ways to solve this problem.

$aleatorio = mt_rand(0, 16777215);
$cor = "#" . dechex($aleatorio);

Then, assuming you want to change the background color of the tag div, add:

background-color: <?php echo $cor ?>;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.