Color inverse

This function inverses a color to it's opposite.
(White to black, blue to yellow, etc.)

function color_inverse($color){
    $color = str_replace('#', '', $color);
    if (strlen($color) != 6){ return '000000'; }
    $rgb = '';
    for ($x=0;$x<3;$x++){
        $c = 255 - hexdec(substr($color,(2*$x),2));
        $c = ($c < 0) ? 0 : dechex($c);
        $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
    }
    return '#'.$rgb;
}
Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
06/13/2006

Updated:
06/13/2006

Tags:



// black -> white
print color_inverse('#000000'); 
// --> returns #ffffff
 
// blue -> yellow
print color_inverse('#0000FF');
// --> #FFFF00

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

HJ June 10, 2011 at 16:37
Adding zeros to the end won't work I think.

Replace " return '000000'; " with the next line:
$color = str_repeat(substr($color,0,1),2).str_repeat(substr($color,1,1),2).str_repeat(substr($color,2,1),2);
Roel October 04, 2010 at 22:20
This code assumes the color code has 6 chars. Color codes don't have to be 6 chars long. You should zeros to the end till it's 6 chars insteed of return 000000. Then this code is perfect.
dasdas June 03, 2010 at 10:30
sadasdas