M
MeshWorld.
Program PHP Tutorial 1 min read

Convert hexadecimal color to rgb or rgba in php

Vishnu Damwala
By Vishnu Damwala

Below PHP helper function converts hex color code string into RGB or RGBA color.

Code

    /**
     * Convert hexadecimal color to rgb or rgba
     *
     * @param string $color
     * @param boolean $getRGBA
     * @param float $opacity
     * @return string
     */
    function hex2rgba(
        string $color,
        bool $getRGBA = true,
        float $opacity = 1
    ): string {
        $output = 'rgb(0,0,0)';

        // Return default color if no color is provided
        if (!$color) {
            return $output;
        }

        // Sanitize $color if "#" is provided
        if ($color[0] == '#') {
            $color = substr($color, 1);
        }

        // Check if color has 6 or 3 characters and get values
        if (strlen($color) == 6) {
            $hex = [
                $color[0] . $color[1],
                $color[2] . $color[3],
                $color[4] . $color[5],
            ];
        } elseif (strlen($color) == 3) {
            $hex = [
                $color[0] . $color[0],
                $color[1] . $color[1],
                $color[2] . $color[2],
            ];
        } else {
            return $output;
        }

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

        //Check for opacity(rgba or rgb)
        if ($getRGBA) {
            $rgb[] = (abs($opacity) > 1) ? 1 : $opacity;
            $output = 'rgba(';
        } else {
            $output = 'rgb(';
        }

        $output .= implode(',', $rgb) . ')';
        //return rgb(a) color string
        return $output;
    }