# \[PHP\] Opposite Colour

**URL:** <https://forum.kirupa.com/t/php-opposite-colour/237547>\
**Category:** open source\
**Created:** [August 31, 2007, 10:05am UTC](https://forum.kirupa.com/t/php-opposite-colour/237547 "2007-08-31T10:05:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![icio](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/icio/32/484_2.png) [@icio](https://forum.kirupa.com/u/icio)\
**Post date:** [August 31, 2007, 10:05am UTC](https://forum.kirupa.com/t/php-opposite-colour/237547/1 "2007-08-31T10:05:03Z")

</div>

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.

```php
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

```php
$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

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

```

Will return the inverse colour of #943839.

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

---

<div class="post-metadata">

**Author:** ![kissole](https://avatars.discourse-cdn.com/v4/letter/k/f6c823/32.png) [@kissole](https://forum.kirupa.com/u/kissole)\
**Post date:** [July 10, 2008, 8:12pm UTC](https://forum.kirupa.com/t/php-opposite-colour/237547/2 "2008-07-10T20:12:52Z")

</div>

> [@evildrummer;2206056](#):
>
> Nice work, similar to my colour functions: [kirupaForum](http://kirupa.com/forum/showthread.php?t=267549%5B6%5D(http://groups.msn.com/TwoGirlsOneCup))

:beer2: Thank you! Good work…

---

<div class="post-metadata">

**Author:** ![Esherido](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/esherido/32/2158_2.png) [@Esherido](https://forum.kirupa.com/u/Esherido)\
**Post date:** [July 10, 2008, 10:08pm UTC](https://forum.kirupa.com/t/php-opposite-colour/237547/3 "2008-07-10T22:08:27Z")

</div>

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