How to create hex colors randomly?

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

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

<div style="color: <?= rand_color()?>">
     Estou colorido!
</div>
Author: Gonçalo Peres 龚燿禄, 2015-12-11

4 answers

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() that creates two arrays, one from 0 to 9 and one from A to F, array_merge() makes combination of them.

Finally a simple while checks if the string already has 7 characters (one sharp followed by six alphanumerics), otherwise it generates a random number between 0 and 15 that is used as an index in $hex which has the 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
Author: rray, 2015-12-11 13:51:26

In php you can do this quite simply:

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

Explaining:

# is the initial character used for hex colors in HTML

%06 it means that 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 capitalized x to generate the capitalized letters of hexadecimal As well.

mt_rand it will generate a random number from 0 to 16777215. The number 16777215 comes from the hexadecimal expression 0xFFFFFF.

Update

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

You can also use it:

function random_color()
{
    return sprintf('#06x', random_int(0, 0xFFFFFF));
}
 9
Author: Wallace Maxters, 2021-02-03 15:12:39

In the detail of the question is asked a solution in PHP, but usually PHP runs in web environments, starting from this presupposition 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 be executed 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 the features of the server side are free and it can easily handle requests. But sending large amounts of data to the client for processing will incur client overhead and make your browsing experience less acceptable, imagine ordering the server for each color? The network may become overloaded and bandwidth consumed. Server-side data processing will increase the server load with each new client.

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

Also, I'm assuming JavaScript is enabled.

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

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

Usage example

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 has several forms that they have already posted here and they are all valid. I would like to introduce a little known strand that is the execution of javascript v8 scripts natively by PHP.

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

You can run javascript with PHP using the extension V8js which runs 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 executed by the interpreter and you can get the output from it, all the functions of V8 are available, which makes you extend the functionality of php to what is perhaps only present in V8.

PHP alternative

Of course, running a V8 Javascript engine might seem a bit of an exaggeration to just generate a random string and maybe you're in an environment that doesn't run anything on the client such as the command line or a REST API. To Approach is always the same, some mathematical function to generate the string and is precisely what the function mt_rand does, generates random numbers, in this case random hexadecimals:

<?php 
printf( "#%06X\n", mt_rand( 0, 0xFFFFFF ));
?>
 3
Author: LeonanCarvalho, 2021-02-11 20:13:03

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 div tag, add:

background-color: <?php echo $cor ?>;
 0
Author: Gonçalo Peres 龚燿禄, 2021-02-10 09:16:30