PHP: Convert a RGB color Array into a Web Hex Code Programming 15 OCT 2010

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!).

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • This arfea of the programming mumbeo jumbo always gives me the hives…

  • this looks great but how do i use it? how do i get the values to the variables? like where are $r $g $b coming from? could you do a proper tutorial that works please :-)