function rgb2hex($r, $g, $b, $uppercase=false, $shorten=false)
{
// The output
$out = "";
// If shorten should be attempted, determine if it is even possible
if ($shorten && ($r + $g + $b) % 17 !== 0) $shorten = false;
// Red, green and blue as color
foreach (array($r, $g, $b) as $c)
{
// The HEX equivalent
$hex = base_convert($c, 10, 16);
// If it should be shortened, and if it is possible, then
// only grab the first HEX character
if ($shorten) $out .= $hex[0];
// Otherwise add the full HEX value (if the decimal color
// is below 16 then we have to prepend a 0 to it)
else $out .= ($c < 16) ? ("0".$hex) : $hex;
}
// Package and away we go!
return $uppercase ? strtoupper($out) : $out;
}
echo rgb2hex(rand(0, 255), rand(0, 255), rand(0, 255), true);