MeshWorld India Logo MeshWorld.
PHP Tutorial Color Conversion hex2rgb 2 min read

Convert Hex to RGB/RGBA in PHP - Complete Guide

Vishnu
By Vishnu
| Updated: May 8, 2026
Convert Hex to RGB/RGBA in PHP - Complete Guide

Converting hex color codes to RGB or RGBA is a common requirement in PHP applications. Whether you’re building a color picker, theme customizer, or processing user input, this guide covers everything you need.

The PHP Function

Here’s a complete, well-documented function that handles both 3-digit and 6-digit hex codes:

php
/**
 * Convert hexadecimal color to RGB or RGBA
 *
 * @param string $color Hex color code (with or without #)
 * @param bool $getRGBA True for RGBA, false for RGB
 * @param float $opacity Opacity value (0-1)
 * @return string RGB or RGBA color string
 */
function hex2rgba(
    string $color,
    bool $getRGBA = true,
    float $opacity = 1
): string {
    $output = 'rgb(0,0,0)';

    if (!$color) {
        return $output;
    }

    // Remove # if present
    if ($color[0] === '#') {
        $color = substr($color, 1);
    }

    // Handle 6-digit and 3-digit hex codes
    if (strlen($color) === 6) {
        $hex = [
            $color[0] . $color[1],
            $color[2] . $color[3],
            $color[4] . $color[5],
        ];
    } elseif (strlen($color) === 3) {
        // Expand 3-digit to 6-digit
        $hex = [
            $color[0] . $color[0],
            $color[1] . $color[1],
            $color[2] . $color[2],
        ];
    } else {
        return $output;
    }

    // Convert hex to decimal
    $rgb = array_map('hexdec', $hex);

    // Build output string
    if ($getRGBA) {
        $rgb[] = min(max($opacity, 0), 1); // Clamp between 0 and 1
        $output = 'rgba(';
    } else {
        $output = 'rgb(';
    }

    return $output . implode(',', $rgb) . ')';
}

Usage Examples

php
// RGB output
echo hex2rgba('#FF5733', false);        // rgb(255,87,51)
echo hex2rgba('3498db', false);         // rgb(52,152,219)

// RGBA with opacity
echo hex2rgba('#FF5733', true, 0.5);    // rgba(255,87,51,0.5)
echo hex2rgba('3498db', true, 0.75);    // rgba(52,152,219,0.75)

// Without # symbol
echo hex2rgba('e74c3c', true);          // rgba(231,76,60,1)

// 3-digit shorthand
echo hex2rgba('#F00', true, 0.8);       // rgba(255,0,0,0.8)

Quick Reference

InputOutput (RGB)Output (RGBA, 0.5)
#FF5733rgb(255,87,51)rgba(255,87,51,0.5)
#3498dbrgb(52,152,219)rgba(52,152,219,0.5)
#fffrgb(255,255,255)rgba(255,255,255,0.5)

Pro Tips

  • Always validate hex input before passing to the function
  • The opacity parameter is automatically clamped between 0 and 1
  • This function is useful for dynamic CSS generation in PHP applications