Generate Pastel Color Based on Name in PHP

Sometimes a plain list of names with alternating colors doesn't make the individual rows pop out as much as is required.


One application I was working on required that each row in a table associated with a certain person be a different color than all the rows associate with other names. Each name would have its own color, and the color had to be the same every time the app was loaded. Oh, and to make it more difficult, the color couldn't be a dark color.


So, the first thing to do was to set up a function that can create the colors:


function get_color($name) {
	$hash = md5($name);

	$color1 = hexdec(substr($hash, 8, 2));
	$color2 = hexdec(substr($hash, 4, 2));
	$color3 = hexdec(substr($hash, 0, 2));
	if($color1 < 128) $color1 += 128;
	if($color2 < 128) $color2 += 128;
	if($color3 < 128) $color3 += 128;
	return "#" . dechex($color1) . dechex($color2) . dechex($color3);

Now that we can generate a color based on the name, we just need to use that in our styles. Here is a quick and dirty example:

$names = array("Kirk","Spock","Bones","Scotty","Sulu","Uhura","Khan");
foreach($names as $name) {
    <div style="background:<?=get_color($name)?>">

And the result is:


Back to Article Index

blog comments powered by Disqus