How to find out if a hex color is light or dark with PHP
In this article we will learn how to find out if a hex color is light or dark in a very interesting way, using only pure PHP!

Hey you programmer, ok? Let’s learn more about PHP!
To check if a color is light or dark, we can use a formula that is made available by the W3C, the web standardization body
The formula is this:
((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
The result of this operation is a value from 0 to 255, which is the lightness of a color
Note that this formula uses the values in RGB, so we need to convert the Hexadecimal to this value
For this action PHP also has specific functions, so it won’t be a problem
Remembering that a color is considered light when the value of this formula is greater than 128
So let’s take a practical example:
<?php $color = '#FFFFFF'; $red = hexdec(substr($color, 1, 2)); $green = hexdec(substr($color, 3, 2)); $blue = hexdec(substr($color, 5, 2)); $result = (($red * 299) + ($green * 587) + ($blue * 114)) / 1000; echo $result;
Here we are analyzing the white color (#FFFFFF) and we receive in the variable $result the maximum brightness value, which is 255
That is, this color is considered light
Also notice that we use substring to get the values we need to convert to RGB, where the first two places of the hex represent R, the two in the middle represent G and the final two represent A.
Pretty cool and easy right? 😀
Conclusion
In this article we learned how to find out if a hex color is light or dark with PHP
We use a formula that is provided by the W3C, where if the result is greater than 128, the color will be considered light.
Also, as it asks for color values in RGB, we convert the hex to RGB before applying the formula with PHP’s hexdec function
Want to learn more about PHP? Click here!
Either line 3 has to be changed to $cor = “#FFFFFF” or 4-6 need $cor updated to $color
it was a typo, sorry
$cor should be $color
thanks Hop!