Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Change the brightness of the passed in hex color in PHP
* Change the brightness of the passed in color
* $diff should be negative to go darker, positive to go lighter and
* is subtracted from the decimal (0-255) value of the color
* @param string $hex color to be modified
* @param string $diff amount to change the color
* @return string hex color
public function hex_color_mod($hex, $diff) {
$rgb = str_split(trim($hex, '# '), 2);
foreach ($rgb as &$hex) {
$dec = hexdec($hex);
if ($diff >= 0) {
$dec += $diff;
else {
$dec -= abs($diff);
$dec = max(0, min(255, $dec));
$hex = str_pad(dechex($dec), 2, '0', STR_PAD_LEFT);
return '#'.implode($rgb);

This comment has been minimized.

Copy link

@clofab clofab commented Jun 5, 2014

Why do you use an if in the loop?
If I'm not mistaken :
$dec -= abs($diff) => $dec -= -$diff (since $diff < 0) => $dec += $diff
So since it would do the same operation anyway, it should be preferable to replace lines 18 to 23 by the addition.

But thank you for that method it helped me generate gradients from any color from the user's theme on my website.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment