CTT – Correios de Portugal check-digit

CTT - Correios de PortugalI 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):

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;
}

Leave a Reply