Find Appropriate Colour In PHP

Use the following function if you want to print the text in a particular colour, depending on what the background colour is.

function opposite($color) {
  $white = 0;
  for ($i = 0; $i < 6; $i += 2) {
    $white += base_convert(substr($color,$i,2),16,10) < 127 ? 1 : 0;
  return $white <= 2 ? "000000" : "ffffff";

It works by looking at the colour and seeing how much of it is white. If greater than two parts are significantly white then the color returned is black, otherwise white is returned.

Here are some examples to test the function out.

echo '<span style="background-color:#ffffff;color:#'.opposite('ffffff').'">XXXXXX</span>';
echo '<span style="background-color:#000000;color:#'.opposite('000000').'">XXXXXX</span>';
echo '<span style="background-color:#fedbad;color:#'.opposite('fedbad').'">XXXXXX</span>';
echo '<span style="background-color:#123456;color:#'.opposite('123456').'">XXXXXX</span>';
echo '<span style="background-color:#fe13ef;color:#'.opposite('fe13ef').'">XXXXXX</span>';



Would love to perpetually get updated great web blog!


Add new comment

The content of this field is kept private and will not be shown publicly.
5 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.