Last Updated: October 10, 2023
·
10.7K
· alesf

Darken HEX color in PHP

I needed to darken user defined colors and came up with this.

It's not very precise (for that I would change it to HSL and change luminosity) and it can't lighten the color, but it serves my needs.

Function:

function darken_color($rgb, $darker=2) {

    $hash = (strpos($rgb, '#') !== false) ? '#' : '';
    $rgb = (strlen($rgb) == 7) ? str_replace('#', '', $rgb) : ((strlen($rgb) == 6) ? $rgb : false);
    if(strlen($rgb) != 6) return $hash.'000000';
    $darker = ($darker > 1) ? $darker : 1;

    list($R16,$G16,$B16) = str_split($rgb,2);

    $R = sprintf("%02X", floor(hexdec($R16)/$darker));
    $G = sprintf("%02X", floor(hexdec($G16)/$darker));
    $B = sprintf("%02X", floor(hexdec($B16)/$darker));

    return $hash.$R.$G.$B;
}

Usage example:

$color = '#45ff33';
$darker = darken_color($color, $darker=2);

echo "$color => $darker";

For best results the value of second parameter should be between 1 and 4 and it can be decimal.

Working example