Invert Hexadeimal Color in PHP

- 1 minute read

The following snippet provides a simple way to invert a given hexadecimal color code string in PHP:

function invertColor($hex) {
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) !== 6) {
        return '#000000';
    }
    $new = '';
    for ($i = 0; $i < 3; $i++) {
        $rgbDigits = 255 - hexdec(substr($hex, (2 * $i), 2));
        $hexDigits = ($rgbDigits < 0) ? 0 : dechex($rgbDigits);
        $new .= (strlen($hexDigits) < 2) ? '0' . $hexDigits : $hexDigits;
    }
    return '#' . $new;
}

And here’s how you can use this function:

echo invertColor('#FFFFFF');
// Echoes "#000000"

Notice how the hash symbol that precedes the string is not technically necessary:

echo invertColor('FFFFFF');
// Echoes "#000000"

However, three-letter shorthand hexadecimal codes are not valid:

echo invertColor('#F0F');
// Echoes "#000000"

Link to this section Conclusion

I hope you found this snippet useful!

I’ve found it indispensable when it comes to working with colors in PHP.