[PHP] Opposite Colour

Needed a quick little function to choose the colour of text that sits over a span with background representative of the colour I want to display.

function oppColour($c, $inverse=false)
{
	if(strlen($c)== 3)
	{ // short-hand
		$c = $c{0}.$c{0}.$c{1}.$c{1}.$c{2}.$c{2};
	}
	if ($inverse)
	{ // => Inverse Colour
		$r = (strlen($r=dechex(255-hexdec($c{0}.$c{1})))<2)?'0'.$r:$r;
		$g = (strlen($g=dechex(255-hexdec($c{2}.$c{3})))<2)?'0'.$g:$g;
		$b = (strlen($b=dechex(255-hexdec($c{4}.$c{5})))<2)?'0'.$b:$b;
		return $r.$g.$b;
	} else
	{ // => Monotone based on darkness of original
		return array_sum(array_map('hexdec', str_split($c, 2))) > 255*1.5 ? '000000' : 'FFFFFF';
	}
}

Calling

$opposite = oppColour('943839');

Will return black or white depending on how bright #943839 is (if dark, white is returned and if light, black is returned).

Whereas calling

$opposite = oppColour('943839', true);

Will return the inverse colour of #943839.

Here’s an example of how I used it: (Click for enlargement)

:beer2: Thank you! Good work…

Holy resurrections, Batman! Anyway, glad Stuart’s amazing wisdom helped you.