green php elephants - elephpantsRGB, that annoying little way of expressing a color via values between 0 and 255 for each of the three components that makes up a color. Always in the form of an array consisting of three values, namely one for red, one for green and one for blue, wouldn’t it be nice if we had a simple function that automatically converted such an array to the more universal web hex code? (Well when I say universal I mean developing on the web).

So let’s do that then. The following little function accepts three inputs, namely the red, green and blue values, converts each to the hexadecimal equivalent with the correct padding (remember a correct hex code is six characters long), concatenates them all together and returns a nice # prefix hex code string for us.

function convertRGBToHex($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;

Simple, clean, and oh so useful (especially when dealing with firefox which seems to enjoy throwing color values as RGB arrays at you!).