Function To Darken A Colour With PHP

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

Good ;)

I used thank you ;)

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.