18th May 2008 - 2 minutes 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 ColourDarken($colour, $dif=20)
{
$colour = str_replace('#','', $colour);
$rgb = '';
if (strlen($colour) != 6) {
// reduce the default amount a little
$dif = ($dif==20)?$dif/10:$dif;
for ($x = 0; $x < 3; $x++) {
$c = hexdec(substr($colour,(1*$x),1)) - $dif;
$c = ($c < 0) ? 0 : dechex($c);
$rgb .= $c;
}
} else {
for ($x = 0; $x < 3; $x++) {
$c = hexdec(substr($colour, (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 ColourDarken('#123456'); // #002042
echo ColourDarken('#666'); // #444
echo ColourDarken('#ffffff'); // #ebebeb
echo ColourDarken('#ffffff',1); // #eeeeee