256 Kilobytes

[PHP] How to generate random, readable background and text color pairs

Articles in Web Development | By August R. Garcia

Published | Last Update

How to generate random, complimentary pairs of dim, bright, pastel, and faded colors using PHP.

965 views, 1 RAM, and 1 comment

While writing a PHP graphing library the other day, it became apparent that code would be needed to generate an arbitrary random colors that did not look terrible. The function below generates random colors and returns an associative array with the color pair.

Two optional parameters are included:

  • $theme
    • By default, generates dim colors (shown in the cover photo for this post). The strings "Dim", "Bright", "Pastel", and "Faded" can optionally be passed as a parameter to generate color pairs of those types.
  • $alt
    • If set to TRUE, then the colors are inverted (for example, if you are generating pie chart slices and want to alternate between dark[er] and light[er] slices)
<?php
  // Generates two complimentary colors 
  function get_color_pair($theme="Dim", $alt=FALSE) {

  // Ignore case
  $theme = ucwords($theme); 

  switch ($theme) {
          case "Dim":
                  $r  = rand(128,255);  $g  = rand(128,255);  $b  = rand(128,255);  $bg  = "rgba($r, $g, $b, 1.0)";
                  $r -= 128;            $g -= 128;            $b -= 128;            $txt = "rgba($r, $g, $b, 1.0)";
                  break;
          case "Bright":
                  $h        =  rand(181,360);
                  $bg  = "hsl(" .  $h      . ", 100%, 50%)";
                  $txt = "hsl(" . ($h-180) . ", 100%, 50%)";
                  break;
          case "Pastel":
                  $h        =  rand(181,360);
                  $bg  = "hsl(" .  $h      . ",  90%, 80%)";
                  $txt = "hsl(" . ($h-180) . ",  90%, 80%)";
                  break;
          case "Faded": 
                  $h        =  rand(181,360);
                  $bg  = "hsl(" .  $h      . ",  90%, 20%)";
                  $txt = "hsl(" . ($h-180) . ",  90%, 20%)";
                  break;
  }
  // Prevent similar colors from being adjacent to each other  
  if ( $alt ) {$t = $txt; $txt = $bg; $bg = $t; }

  return ['BG' => $bg, 'TXT'=>$txt];
}

The code snippet shown below can be used to test the color outputs, such as through a tool like PHP Tester.

<?php
function test_p($t) {
    $bg  = $t['BG' ];	
    $txt = $t['TXT'];
	echo "<p style='padding:1em .5em;font-weight:bold;background-color:$bg;color:$txt;'>$txt on a $bg background</p>"; 
	echo "<hr />";
};

$t = get_color_pair()                ; echo "<h3>Default     </h3>"  ; test_p($t);
$t = get_color_pair("Dim")           ; echo "<h3>Dim         </h3>"  ; test_p($t);
$t = get_color_pair(Dim, TRUE)     ; echo "<h3>Dim (Alt)   </h3>"  ; test_p($t);

$t = get_color_pair("Bright")        ; echo "<h3>Bright      </h3>"  ; test_p($t);
$t = get_color_pair(Bright, TRUE)  ; echo "<h3>Bright (Alt)</h3>"  ; test_p($t);

$t = get_color_pair("Pastel")        ; echo "<h3>Pastel      </h3>"  ; test_p($t);
$t = get_color_pair(Pastel, TRUE)  ; echo "<h3>Pastel (Alt)</h3>"  ; test_p($t);

$t = get_color_pair("Faded")         ; echo "<h3>Faded      </h3>"   ; test_p($t);
$t = get_color_pair(Faded, TRUE)   ; echo "<h3>Faded (Alt)</h3>"   ; test_p($t);

Additional reading:

Users Who Have Downloaded More RAM:
Hash Brown (1 year ago)
🐏 ⨉ 1
Posted by August R. Garcia 1 year ago

Edit History

• [2018-12-03 14:29 PST] August R. Garcia (1 year ago)
• [2018-12-03 14:29 PST] August R. Garcia (1 year ago)
• [2018-12-03 14:29 PST] August R. Garcia (1 year ago)
• [2018-12-03 14:29 PST] August R. Garcia (1 year ago)
• [2018-12-03 14:29 PST] August R. Garcia (1 year ago)
• [2018-12-03 14:29 PST] August R. Garcia (1 year ago)
🕓 Posted at 03 December, 2018 14:29 PM PST

Profile Photo - August R. GarciaAugust R. GarciaLARPing as a Sysadmi...Portland, ORSite Owner

August Garcia is some guy who used to sell Viagra on the Internet. He made this website to LARP as a sysadmin while posting about garbage like user-agent spoofing, spintax, the only good keyboard, virtual assitants from Pakistan, links with the rel="nofollow" attributeproxiessin, the developer console, literally every link building method, and other junk.

Available at arg@256kilobytes.com, via Twitter, or arg.256kilobytes.com. Open to business inquiries based on availability.

Profile Photo - August R. GarciaAugust R. GarciaLARPing as a Sysadmi...Portland, ORSite Owner

Updated version of the function in the original post that supports setting an alpha/opacity value:

// Generates two complimentary colors 
function get_color_pair($theme="Dim", $alt=FALSE, $bg_a=1.0, $txt_a=1.0, $as_string=FALSE) {
  // Ignore case
  $theme = ucwords($theme);
  switch ($theme) {
          case "Dim":
                  $r  = rand(128,255);  $g  = rand(128,255);  $b  = rand(128,255);  $bg  = "rgba($r, $g, $b, $bg_a )";
                  $r -= 128;            $g -= 128;            $b -= 128;            $txt = "rgba($r, $g, $b, $txt_a)";
                  break;
          case "Bright":
                  $h        =  rand(181,360);
                  $bg  = "hsla(" .  $h      . ", 100%, 50%, $bg_a )";
                  $txt = "hsla(" . ($h-180) . ", 100%, 50%, $txt_a)";
                  break;
          case "Pastel":
                  $h        =  rand(181,360);
                  $bg  = "hsla(" .  $h      . ",  90%, 80%, $bg_a )";
                  $txt = "hsla(" . ($h-180) . ",  90%, 80%, $txt_a)";
                  break;
          case "Faded":
                  $h        =  rand(181,360);
                  $bg  = "hsla(" .  $h      . ",  90%, 20%, $bg_a )";
                  $txt = "hsla(" . ($h-180) . ",  90%, 20%, $txt_a)";
                  break;
  }
  // Prevent similar colors from being adjacent to each other  
  if ( $alt ) {$t = $txt; $txt = $bg; $bg = $t; }

  if ($as_string)
    return " style='color:$txt;background-color:$bg;' ";
  return ['BG' => $bg, 'TXT'=>$txt];
}

Also:

Chart.JS Automatic Colors/BackgroundColor

function assoc_to_chartjs_inputs($assoc, $theme="Bright") {
        $colors = [];
        $alt = 0;
        foreach ($assoc as $t) {
                //$colors[] = "#" . dechex(mt_rant(0, 16777215)) . "84"; 
                //$colors[] = "#" . dechex(mt_rand(0, 14777215)) . "84"; 
                $colors[] = get_color_pair($theme, ($alt++ % 2), 0.515, 0.515, FALSE)['BG'];
        }
        $vals = [
                'lbls'   => json_encode(array_keys(  $assoc)),
                'data'   => json_encode(array_values($assoc)),
                'colors' => json_encode(array_values($colors    ))
        ];
        return $vals;
}

Example usage:

<?php
$all_tld_counts = [
  "com" => 109,
  "org" => 75,
  "net" => 11
]; 
$inputs = assoc_to_chartjs_inputs($all_tld_counts);
?>


<h3>TLD Frequencies</h3>
<canvas id="our_data_2" width="400" height="200"></canvas>
<script>
var ctx = document.getElementById('our_data_2').getContext('2d');
var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: <?=$inputs['lbls'];?>, 
            datasets: [{
                backgroundColor: <?=$inputs['colors'];?>, 
                data: <?=$inputs['data'];?>  
            }]
        }, 
        options: { legend: { display: false } }
});
</script>

Download more RAM. 🐏 ⨉ 0Posted by August R. Garcia 8 months ago

Edit History

• [2019-09-30 14:11 PDT] August R. Garcia (8 months ago)
🕓 Posted at 30 September, 2019 14:11 PM PDT

Sir, I can do you a nice SEO.

Post a New Comment

Do you like having a good time?

Register an Account

You can also login to an existing account or reset your password. All use of this site is subject to the terms of service and privacy policy.

Read Quality Articles

Read some quality articles. If you can manage to not get banned for like five minutes, you can even post your own articles.

View Articles →

Argue with People on the Internet

Use your account to explain why people are wrong on the Internet forum.

View Forum →

Vandalize the Wiki

Or don't. I'm not your dad.

View Wiki →

Ask and/or Answer Questions

If someone asks a terrible question, post a LMGTFY link.

View Answers →

Make Some Money

Hire freelancers and/or advertise your goods and/or services. Hire people directly. We're not a middleman or your dad. Manage your own business transactions.

Register an Account