Question: I want users on my website to be able to pick a hex colour, and I just want to display white text for dark colours and black text for light colours. Can you work out the brightness from a hex code (preferably PHP)?

Answer: 
```
$hex = "78ff2f"; //Bg color in hex, without any prefixing #!

//break up the color in its RGB components
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));

//do simple weighted avarage
//
//(This might be overly simplistic as different colors are perceived
// differently. That is a green of 128 might be brighter than a red of 128.
// But as long as it's just about picking a white or black text color...)
if($r + $g + $b > 382){
    //bright color, use dark font
}else{
    //dark color, use bright font
}

```
I tried a different approach to this, I used HSL (hue, saturation & lightness) lightness percentage to check if the color is dark or light. (like @chrisf said in his answer)

**function:**

```
function colorislight($hex) {
   $hex       = str_replace('#', '', $hex);
   $r         = (hexdec(substr($hex, 0, 2)) / 255);
   $g         = (hexdec(substr($hex, 2, 2)) / 255);
   $b         = (hexdec(substr($hex, 4, 2)) / 255);
   $lightness = round((((max($r, $g, $b) + min($r, $g, $b)) / 2) * 100));
   return ($lightness >= 50 ? true : false);
}

```

On the return line it checks if the lightness percentage is higher than 50% and returns true otherwise false is returned. You can easily change it to return true if the color has 30% lightness and so on. The `$lightness` variable can return from 0 to 100 0 being the darkest and 100 being the lightest.

**how to use the function:**

```
$color = '#111111';
if ( colorislight($color) ) {
   echo 'this color is light';
}
else {
   echo 'this color is dark';
}

```