Marco Gonçalves

CTT – Correios de Portugal check-digit

I was unable to find anywhere a Portuguese national postal service, package registry number check-digit validation. So, I politely asked them and soon after a PDF describing the algorithm was on my desk.

It’s pretty simple and standard stuff (only an awkward multiplier order of each digit), so the best way to describe it’s with a validation function in PHP (even for non PHP users/programmers should be simple to enough to understand at a glance):

function checkDigitCTT($ref) {
    if (! preg_match('/^[a-z]{2}[0-9]{9}[a-z]{2}$/i', $ref))
        return false;
            
    $digits      = substr($ref, 2, 9);
    $multipliers = array(8,6,4,2,3,5,9,7);
        
    $tmp = 0;
    foreach ($multipliers as $k => $v)
        $tmp = $tmp + (((int) $digits[$k]) * $v);
			
    $tmp = round($tmp % 11);

    if ($tmp == 0)
        $check_digit = 5;
    else if ($tmp == 1)
        $check_digit = 0;
    else
        $check_digit = 11 - $tmp;
			
    if ($check_digit == ((int) $digits[8]))
        return true;

    return false;
}
Exit mobile version