PHP

RGB ↔ Hex Conversion

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Two-way conversion between #RRGGBB hex strings and [R, G, B] arrays. Handy when working with theme colors that come from both sources (CSS strings vs. RGB sliders).
PHP
Raw
<?php
function rgbToHex(int $r, int $g, int $b): string {
    return sprintf('#%02x%02x%02x', $r & 0xFF, $g & 0xFF, $b & 0xFF);
}

function hexToRgb(string $hex): array {
    $hex = ltrim($hex, '#');
    if (strlen($hex) === 3) {
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    }
    if (strlen($hex) !== 6) throw new InvalidArgumentException("Bad hex color: $hex");
    return [
        hexdec(substr($hex, 0, 2)),
        hexdec(substr($hex, 2, 2)),
        hexdec(substr($hex, 4, 2)),
    ];
}

echo rgbToHex(56, 189, 248);     // #38bdfa
print_r(hexToRgb('#34d399'));    // [52, 211, 153]
print_r(hexToRgb('#fff'));       // [255, 255, 255]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.