Skip to content

Instantly share code, notes, and snippets.

@vensires
Created October 10, 2017 08:07
Show Gist options
  • Save vensires/54460171f2b4334c2502abf793c53653 to your computer and use it in GitHub Desktop.
Save vensires/54460171f2b4334c2502abf793c53653 to your computer and use it in GitHub Desktop.
Turns a HEX color to a darker/lighter shade. If your needs are more intensive and you require more that just a function, you could check the phpColors repo: https://github.com/mexitek/phpColors
<?php
/**
* Turns a HEX color to a darker/lighter shade.
*
* @param string $colorstr
* The color as a HEX string with a # prefix.
* @param int $steps
* The number of steps to alter the color to. Both negavive and positive
* numbers are allowed.
*
* @return string
* The modified HEX string.
*/
function darkenlight($colorstr, $steps) {
$colorstr = str_replace('#', '', $colorstr);
$rhex = substr($colorstr, 0, 2);
$ghex = substr($colorstr, 2, 2);
$bhex = substr($colorstr, 4, 2);
$r = hexdec($rhex);
$g = hexdec($ghex);
$b = hexdec($bhex);
$r = max(0, min(255, $r + $steps));
$g = max(0, min(255, $g + $steps));
$b = max(0, min(255, $b + $steps));
return '#' . dechex($r) . dechex($g) . dechex($b);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment