What are the best practices for implementing the LZW compression algorithm for image data in the GIF format using PHP?

When implementing the LZW compression algorithm for image data in the GIF format using PHP, it is important to follow best practices to ensure efficient compression and decompression. This includes properly initializing the dictionary, handling variable-length codes, and ensuring that the compressed data is correctly formatted for the GIF format.

function LZWCompress($data) {
    $dictionarySize = 256;
    $dictionary = array_flip(range("\0", "\xFF"));
    $compressedData = [];
    $buffer = '';
    
    foreach(str_split($data) as $char) {
        $buffer .= $char;
        if(!isset($dictionary[$buffer])) {
            $compressedData[] = $dictionary[$buffer];
            $dictionary[$buffer] = $dictionarySize++;
            $buffer = $char;
        }
    }
    
    if($buffer !== '') {
        $compressedData[] = $dictionary[$buffer];
    }
    
    return $compressedData;
}