What are the potential pitfalls of using PHP functions like hexdec() and substr() when converting color values, and how can they be avoided?

The potential pitfalls of using PHP functions like hexdec() and substr() when converting color values include incorrect conversions due to leading zeros being removed or not properly handling alpha values in hex codes. To avoid these issues, it is recommended to use functions like sscanf() for hex to RGB conversion and sprintf() for RGB to hex conversion.

// Fix for converting hex to RGB
function hexToRgb($hex) {
    list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
    return [$r, $g, $b];
}

// Fix for converting RGB to hex
function rgbToHex($r, $g, $b) {
    return sprintf("#%02x%02x%02x", $r, $g, $b);
}