Working with Hex Colors in PHP

I was tinkering with a devotion schedule application this morning, and needed to have an automatically handled font color so that a series of lines would be a gradient.

Here’s how to work with automatic gradients (or colors in general) in PHP.

First off, we’re working with hex. The functions you’ll find useful are hexdec() and dechex(). hexdec takes a hex number and converts it to decimal, while dechex does the opposite.

In hex, black is #000000, or 00 00 00. These three bytes represent the values for red, green, and blue (RGB) respectively. White is #ffffff, or ff ff ff. Gray colors are any combination in between, as long as the bytes for red, green, and blue are equal. (i.e. d6d6d6, 8e8e8e, 4b4b4b, etc…)

Thus, to lighten a black, all you need to do is add some value equally to each of the three bytes. (i.e. if you add the hex value 7f to each, you’ll end up with 7f7f7f, a middle gray.)

Let’s move on to some code examples…

I’ve found it to be useful to represent hex triplets using arrays. This way, you can always implode() to obtain the string version. Here’s how to represent black (#000000).

$color = array("00", "00", "00");

If you wanted to use it somewhere, you could just implode it:

<?php
$black = implode($color);
echo "<font style='color: #{$black}'>Hello this is black font</font>";
?>

Here’s how you can easily add an equal amount to each value, creating a gray:

for($i = 0; $i < count($color); $i++) {
     $color[$i] = dechex(hexdec($color[$i]) + hexdec("7f"));
}

Here’s an example where we continue to add the value 19 for each div over 6 divs, creating a gradient of divs:

for($c = 0; $c < 6; $c++) {

   $color = array("00", "00", "00");

   for($i = 0; $i < count($color); $i++) {
      $color[$i] = dechex(hexdec($color[$i]) + hexdec("19" * $c));
   }

   $color = implode($color);

   echo "<div style='color: #fff; width: 100px; height: 100px; float: left;
background-color: #{$color};'>{$color}</div>";

}

Here is what it looks like in action:

000
191919
383838
575757
767676
959595
 

Neat huh? For dynamic design templates where colors need to be automatically generated based on a user selected base value, you can use this technique to create lighter and darker versions of the user selected color to make the design a little more dynamic.

It could take a little extra hacking though, since universally applying the same algorithm to all user selected colors will create bugs for corner cases.