treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Random Hex Color

Last updated on:

Technique #1

<?php 
    
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    
?>

Then echo out the $color value anywhere you need it. For example:

<body style="background: <?php echo $color; ?>;">

Technique #2

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

There is also a JavaScript version.

Reference URL

View Comments

Comments

  1. Simpler version:

    <php $color = sprintf(“#%06x”,rand(0,16777215)); ?>

    <body style="background: <php echo $color; ?>;”>

  2. Interestingly enough, I had to do this exact task just a few days ago. Here’s what I came up with:

    $color = str_pad(dechex(rand(0,16777215),6, "0", STR_PAD_LEFT);

  3. In technique #1 you can tweak with the code to get Red, Green and Blue shades out of the code. The all you have to play with is the value upto 15.

  4. TerryB
    Permalink to comment#

    Can I randomize hex colours from a preset list of colour hexes? If so then how?

    • purpletoad
      Permalink to comment#

      yes you can with #1, but your preset list must have some common number such as #axbxcx or #aabbxx

  5. purpletoad
    Permalink to comment#

    for the solution #1, you can actually contorl the random color where #2 cannot

  6. How about this one?

    $rand = dechex(rand(0x000000, 0xFFFFFF));
    echo('#' . $rand);

    You can change rand in for mt_rand if you want, and you can put strtoupper() around the dechex to make the random number look nicer (although it’s not required). That would look like $rand = strtoupper(dechex(rand(0x000000, 0xFFFFFF)));

    It works perfectly and is way simpler than all the other methods described here :)

Leave a Comment

Use markdown or basic HTML and be nice.