Coloring with PHP: Common Functions for Everyday Use Case

—   Aryan K on Sep 24, 2021
Last Modified : Apr 21, 2024

Colors are an important part of design, they add meaning and flavor to a piece. Color theory, the art and science of colors also higlights the importance of colors as psychological tool. So, often times you may want them to be dynamic on your web pages or apps. In this post, we'll go on to all the potential use cases of colors and how to work them all out with PHP Code. Please note that I am using PHP code to demonstrate the features, but the algorithms will be equally well applicable to all other languages.

#1. Generate Unique Colors from String

If you want to higlight a text or a word so that it has a unique color based on how it is spelled you can use the code below. Using this function, a specific word or a string will always output a specific hex color like a hash function. The uses cases may include highligting tags, categories, or any other piece of text. For eg. the word "apple" outputs "#a92ed0" hex color, so whenver you use the word "apple" this function will output the same color always. Read the explanation below to understand how it works.

   * Assign Color to String
   public function stringColor(string $string)
      $code = dechex(crc32($string));
      return '#'.substr($code, 0, 6);        

Let's understand how it works?

So we know a hex color is represented by a six letter hex string and it ranges from #000000 to #ffffff, with every two characters representing a set of colors for eg. #ff0000 represents the red color #00ff00 represents green and so on. So basically any hex string with 6 letter of length can be used to represent a color. But that wont appear very cool, right? Okay, we are just learning things up!

Great! Now, we can directly convert a string to hexadecimal representation and then simply extracting 6 letters out of the resulting hex string and use it as a color though that might not look very pretty in accordance with your color scheme but as I said we are learning things here. You may also use these techniques as you've understood the concept here.

  function stringColor(string $string)
    // As md5 returns hex string we can do:
     return '#'.substr(md5($string), 0, 6);

Well, you can also directly use bin2hex() method to generate HEX values from a string, but it is better to hash the string value to produce a fixed length hash rather than supplying a big input chunk.

Please note that colors generated this way wont be much suitable with your application's color scheme. You should better generate colors with varying HUEs only and for that you may want to convert HEX to RGB to HSL Color scheme and back. This PHP Color (mexitek/phpColors) library provides helpers for color conversion with PHP.

#2. Given a Color Get a Contrast Color

Sometimes low color contrast make texts illegible. This function below calculates an output color either black or white, based on the input given color. The output color will always be in perfect contrast from the input color. For eg. If the color is purely white then resulting output will be black and similar. Please note I did not write the algorithm, I have just compiled it for reference.

     * Compare & Return Contrast from Hex Color
	public contrastColor(string $hexColor) : string
		// hexColor RGB
        $R1 = hexdec(substr($hexColor, 1, 2));
        $G1 = hexdec(substr($hexColor, 3, 2));
        $B1 = hexdec(substr($hexColor, 5, 2));

        // Black RGB
        $blackColor = "#000000";
        $R2BlackColor = hexdec(substr($blackColor, 1, 2));
        $G2BlackColor = hexdec(substr($blackColor, 3, 2));
        $B2BlackColor = hexdec(substr($blackColor, 5, 2));

         // Calc contrast ratio
         $L1 = 0.2126 * pow($R1 / 255, 2.2) +
               0.7152 * pow($G1 / 255, 2.2) +
               0.0722 * pow($B1 / 255, 2.2);

        $L2 = 0.2126 * pow($R2BlackColor / 255, 2.2) +
              0.7152 * pow($G2BlackColor / 255, 2.2) +
              0.0722 * pow($B2BlackColor / 255, 2.2);

        $contrastRatio = 0;
        if ($L1 > $L2) {
            $contrastRatio = (int)(($L1 + 0.05) / ($L2 + 0.05));
        } else {
            $contrastRatio = (int)(($L2 + 0.05) / ($L1 + 0.05));

        // If contrast is more than 5, return black color
        if ($contrastRatio > 5) {
            return '#000000';
        } else {
            // if not, return white color.
            return '#FFFFFF';

Let's understand how it works?

This function accepts a Hex Color String as an argument and transforms it to an RGB color space(Line: 6-9), it does the same for the black color (Line: 11-15). We then calculate the contrast ratio which is the ratio between the maximum and the minimum brightness. L1 and L2 are relative luminance of lighter of colors and darker of colors respectively. Now, on line 34, we check if hte contrast ratio is greater or less than 5 and return white or black color whichever suits.

#3. Highlighting PHP Syntax with PHP itself

When using PHP Code samples on this website, I needed a way to highlight PHP Syntax, though Javascript libraries are perfect for the need but I wanted someting server side. Guess what PHP has a special built-in function called highlight_string() that does the job perfectly well.

The function accepts a string argument, a valid php syntax wrapped in a string and it wll highlight it perfectly well using built-in colors. It outputs a valid HTML <pre><code></code></pre> code syntax. I used the following code and got the output as show below

highlight_string('<?php echo "Hello World!" ?>');
HTML Output:
<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">echo&nbsp;</span><span style="color: #DD0000">"Hello&nbsp;World!"&nbsp;</span><span style="color: #0000BB">?&gt;</span>
Rendered as:
<?php echo "Hello World!" ?>

There's a similar function highlight_file() that accepts a file path as an argument and output the valid html code to highlight PHP syntaxes within the file. Find more details about it here highlight_file()


PHP is a mature language with lots of super features that sets it apart. In this guide we saw few of the everyday use cases and requirements related to colors, but there are still a vast number of things to know. These were a few of the things I wanted for myself and thus shared it with you here to benefit both of us. In the upcoming guides I will be taking this topic in-depth. If you have questions, feedback or suggestions, you're welcome in the comments. Keep learning, keep growing!

Tags: PHP PHP Functions Colors