Posted by & filed under Programming.

Needed to create a list of the web safe colors for another site of mine. Yeah, I know that web safe colors are outdated. But it was still something I wanted on the site.

Typing in 216 hex color codes was not something I wanted to do though.

Looking over a list of the safe colors I noticed that every color was made up of only the hex pairs 00, 33, 66, 99, cc, and ff. Or, in decimal, 0, 51, 102, 153, 204, and 255. That made it pretty easy to loop through and create the RGB values.

function get_websafe() {
    $vals = array(0, 51, 102, 153, 204, 255);
    $colors = array();
    foreach ($vals as $r) {
        foreach ($vals as $g) {
            foreach ($vals as $b) {
                $colors[] = rgbToHex($r, $g, $b);
            }
        }
    }
    return $colors;
}

Also needed the rgbToHex function, but that was something that was already in place. I’ll go ahead and list it below.

function rgbToHex($r, $g, $b) {
	$hex = '';
	$hex .= str_pad(dechex($r), 2, '0', STR_PAD_LEFT);
	$hex .= str_pad(dechex($g), 2, '0', STR_PAD_LEFT);
	$hex .= str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
	return $hex; 
}

You can see the results here.

Leave a Reply

Your email address will not be published. Required fields are marked *