<?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]
Create a free account and build your private vault. Share publicly whenever you want.