Home » Php » random – PHP generate RGB

random – PHP generate RGB

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m facing this situation where I have an ID which comes from a database (so it can be 1, 100, 1000, …) and I need to generate random colors, however equal ID’s should result in the same color.

Any suggestion on how I can achieve this?

Thanks!

How to&Answers:

Use a cryptographic hash and clip the bytes you don’t need:

function getColor($num) {
    $hash = md5('color' . $num); // modify 'color' to get a different palette
    return array(
        hexdec(substr($hash, 0, 2)), // r
        hexdec(substr($hash, 2, 2)), // g
        hexdec(substr($hash, 4, 2))); //b
}

The resulting (code to generate it) looks like this for the numbers 0-20:

demo output

Answer:

<?php 
// someting like this?
$randomString = md5($your_id_here); // like "d73a6ef90dc6a ..."
$r = substr($randomString,0,2); //1. and 2.
$g = substr($randomString,2,2); //3. and 4.
$b = substr($randomString,4,2); //5. and 6.
?>
<style>
#topbar { border-bottom:4px solid #<?php echo $r.$g.$b;  ?>; }
</style>

Answer:

The obvious approach is to just convert the ID into a color (e.g. lower 8 bits are the blue, next 8 bits are Green, next 8 are Red – leave 8 bits, but I’m sure you can figure that out 😉

Assuming this doesn’t work (cos you end up with a horrible color palette:
Use an array (or hash table) to make a mapping of IDs to Colors.

If you are concerned that there are too many IDs, then you could apply some hash to the ID and use that as you key into the “id to color” mapping. In this case you are effectively saying one id always has one color, but one color can be used by many IDs.

Answer:

If the array is always sorted, you can use this algorythm up to 250 items:

<?php
function getRGBColorString( $array )
{
    $indexColor = round( 250 / count( $array ) );
    $iterator = 1;

    $arrayOfRGB = array();

    foreach( $array as $item)
    {   
        $arrayOfRGB[] = "rgb(" . ( $indexColor * $iterator ) . ", 113, 113 )";
        $iterator++;
    }  

    return $arrayOfRGB;
}

?>