Function To Darken A Colour With PHP

18th May 2008 - 1 minute read time

The following function will reduce a hexadecimal colour string by a set value. It can take three and six digit colour values.

function ColorDarken($color, $dif=20)
{
 $color = str_replace('#','', $color);
 $rgb = '';
 if (strlen($color) != 6) {
  // reduce the default amount a little
  $dif = ($dif==20)?$dif/10:$dif;
  for ($x = 0; $x < 3; $x++) {
   $c = hexdec(substr($color,(1*$x),1)) - $dif;
   $c = ($c < 0) ? 0 : dechex($c);
   $rgb .= $c;
  }
 } else {
  for ($x = 0; $x < 3; $x++) {
   $c = hexdec(substr($color, (2*$x),2)) - $dif;
   $c = ($c < 0) ? 0 : dechex($c);
   $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
  }
 }
 return '#'.$rgb;
}

Here are some examples of use.

echo ColorDarken('#123456'); // #002042
echo ColorDarken('#666'); // #444
echo ColorDarken('#ffffff'); // #ebebeb
echo ColorDarken('#ffffff',1); // #eeeeee

Comments

Permalink

Good ;)

I used thank you ;)

Anon (Fri, 01/06/2012 - 19:24)

Add new comment

The content of this field is kept private and will not be shown publicly.